如何验证JavaScript中对象的存在?

以下工作:

if (!null)
   alert("GOT HERE");

但是这会抛出一个错误:

if (!maybeObject)
   alert("GOT HERE");

错误:

maybeObject没有定义。


当前回答

除了检查对象/变量是否存在之外,您可能希望提供一个“最坏情况”输出,或者至少将其捕获到警报中,这样就不会被忽略。

检查、提供替代方案和捕捉错误的函数示例。

function fillForm(obj) {
  try {
    var output;
    output = (typeof obj !== 'undefined') ? obj : '';
    return (output);
  } 
  catch (err) {
    // If an error was thrown, sent it as an alert
    // to help with debugging any problems
    alert(err.toString());
    // If the obj doesn't exist or it's empty 
    // I want to fill the form with ""
    return ('');
  } // catch End
} // fillForm End

我创建这个也是因为我传递给它的对象可能是x, x.m, x.m[z],如果x.m不存在,则typeof x.m[z]将失败并报错。

我希望这能有所帮助。(顺便说一下,我是JS新手)

其他回答

你可以安全地在未定义的变量上使用typeof操作符。

如果它被赋值,包括null, typeof将返回非undefined的值。Typeof总是返回一个字符串。

因此

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}

你可以使用:

if (typeof objectName == 'object') {
    //do something
}

将文本框值设置为一帧到内联帧使用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

你可以使用typeof测试本地对象:

if (typeof object !== "undefined") {}

全局变量窗口

你可以通过检查window对象来测试全局对象(在全局作用域中定义的对象):

if (window.FormData) {}

我觉得这样最简单

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");