如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
当前回答
将文本框值设置为一帧到内联帧使用div对齐选项卡面板。 所以首先,在设置值之前,我们需要检查所选择的标签面板框架可用或不使用以下代码:
Javascript代码:
/////////////////////////////////////////
<script>
function set_TextID()
{
try
{
if(!parent.frames["entry"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["entry"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["education"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["education"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["contact"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["contact"].document.getElementById("form_id").value=setText;
}
}catch(exception){}
}
</script>
其他回答
你可以安全地在未定义的变量上使用typeof操作符。
如果它被赋值,包括null, typeof将返回非undefined的值。Typeof总是返回一个字符串。
因此
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
我觉得这样最简单
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
if (maybeObject !== undefined)
alert("Got here!");
如果你只关心它的存在(它被宣布了吗?),认可的答案就足够了:
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
如果你关心它的实际值,你应该添加:
if (typeof maybeObject != "undefined" && maybeObject != null ) {
alert("GOT THERE");
}
As typeof(null) == "object"
例如:bar = {x: 1, y: 2, z: null}
typeof( bar.z ) == "object"
typeof( bar.not_present ) == "undefined"
通过这种方式,您可以检查它既不是null也不是undefined,并且由于typeof在value不存在的情况下不会出错加上&&短路,因此您永远不会得到运行时错误。
就我个人而言,我建议在某个地方添加一个helper fn(让我们不要相信typeof()):
function exists(data){
data !== null && data !== undefined
}
if( exists( maybeObject ) ){
alert("Got here!");
}
这个帖子很久以前就被打开了。同时,我认为使用三元运算符是最简单的选择:
maybeObject ? console.log(maybeObject.id) : ""