简体   繁体   English

检查 JavaScript 中是否存在对象

[英]Check if object exists in JavaScript

How do I verify the existence of an object in JavaScript?如何验证 JavaScript 中对象的存在?

The following works:以下工作:

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

But this throws an Error:但这会引发错误:

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

The Error:错误:

maybeObject is not defined. maybeObject没有定义。

You can safely use the typeof operator on undefined variables.您可以安全地对未定义的变量使用typeof运算符。

If it has been assigned any value, including null, typeof will return something other than undefined.如果已为其分配任何值,包括 null,则 typeof 将返回 undefined 以外的内容。 typeof always returns a string. typeof 总是返回一个字符串。

Therefore所以

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

There are a lot of half-truths here, so I thought I make some things clearer.这里有很多半真半假的,所以我想我把一些事情说清楚了。

Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).实际上,您无法准确判断变量是否存在(除非您想将每一行都包装到 try-catch 块中)。

The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined原因是 Javascript 有这个臭名昭著的undefined值,这显然并不意味着变量没有定义,或者它不存在undefined !== not defined

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

So both a variable that exists and another one that doesn't can report you the undefined type.因此,存在的变量和不存在的变量都可以向您报告undefined类型。

As for @Kevin's misconception, null == undefined .至于@Kevin 的误解, null == undefined It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values.这是由于类型强制,这也是 Crockford 不断告诉每个不确定这种事情的人始终使用严格相等运算符===来测试可能的假值的主要原因。 null !== undefined gives you what you might expect. null !== undefined为您提供您所期望的。 Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null .另请注意, foo != null可以是检查变量是否既不是undefined也不是null的有效方法。 Of course you can be explicit, because it may help readability.当然,您可以明确表示,因为这可能有助于提高可读性。

If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused.如果您将问题限制为检查对象是否存在, typeof o == "object"可能是一个好主意,除非您不考虑数组对象,因为这也将报告为可能离开您的object类型有点困惑。 Not to mention that typeof null will also give you object which is simply wrong.更不用说typeof null也会给你一个完全错误的object

The primal area where you really should be careful about typeof , undefined , null , unknown and other misteries are host objects.您真正应该注意typeofundefinednullunknown和其他问题的主要区域是宿主对象。 They can't be trusted.他们不能被信任。 They are free to do almost any dirty thing they want.他们几乎可以自由地做他们想做的任何肮脏的事情。 So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.因此,请小心使用它们,如果可以,请检查功能,因为这是使用甚至可能不存在的功能的唯一安全方式。

You can use:您可以使用:

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

Two ways.两种方式。

typeof for local variables局部变量的 typeof

You can test for a local object using typeof:您可以使用 typeof 测试本地对象:

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

window for global variables全局变量窗口

You can test for a global object (one defined on the global scope) by inspecting the window object:您可以通过检查 window 对象来测试全局对象(在全局范围内定义的对象):

if (window.FormData) {}

如果这是一个全局对象,你可以使用if (!window.maybeObject)

You could use "typeof".你可以使用“typeof”。

if(typeof maybeObject != "undefined")
    alert("GOT HERE");

I used to just do a if(maybeObject) as the null check in my javascripts.我曾经只是在我的 javascripts 中做一个if(maybeObject)作为空检查。

if(maybeObject){
    alert("GOT HERE");
}

So only if maybeObject - is an object, the alert would be shown.所以只有当maybeObject - 是一个对象时,才会显示警报。 I have an example in my site.我的网站上有一个例子。

https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes

I've just tested the typeOf examples from above and none worked for me, so instead I've used this:我刚刚测试了上面的typeOf示例,但没有一个对我有用,所以我使用了这个:

 btnAdd = document.getElementById("elementNotLoadedYet"); if (btnAdd) { btnAdd.textContent = "Some text here"; } else { alert("not detected!"); }

The thread was opened quite some time ago.该线程已在很久以前打开。 I think in the meanwhile the usage of a ternary operator is the simplest option:我认为同时使用三元运算符是最简单的选择:

maybeObject ? console.log(maybeObject.id) : ""

If you care about its existence only ( has it been declared ? ), the approved answer is enough :如果您只关心它的存在(是否已声明?),批准的答案就足够了:

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

If you care about it having an actual value, you should add:如果您关心它具有实际价值,您应该添加:

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

As typeof( null ) == "object"由于typeof( null ) == "object"

eg bar = { x: 1, y: 2, z: null}例如bar = { x: 1, y: 2, z: null}

typeof( bar.z ) == "object" 
typeof( bar.not_present ) == "undefined" 

this way you check that it's neither null or undefined , and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.通过这种方式,您可以检查它既不是null也不是undefined ,并且由于如果 value 不存在加上&&短路, typeof不会出错,因此您永远不会遇到运行时错误。

Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):就我个人而言,我建议在某处添加一个助手 fn (并且让我们不要相信typeof() ):

function exists(data){
   data !== null && data !== undefined
}

if( exists( maybeObject ) ){
    alert("Got here!"); 
}

You can use the ! 您可以使用! operator twice !! 操作员两次!! :

if (!!maybeObject) {
  alert("maybeObject exists");
}

Or one time ! 还是一次! for not exists: 对于不存在:

if (!maybeObject) {
  alert("maybeObject does not exist");
}

What is the !! 是什么 !! (not not) operator in JavaScript? (不是)JavaScript中的运算符?

Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.除了检查对象/变量的存在之外,您可能还想提供“最坏情况”输出或至少将其捕获到警报中,以免被忽视。

Example of function that checks, provides alternative, and catch errors.检查、提供替代和捕获错误的函数示例。

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

I created this also because the object I was passing to it could be x , xm , xm[z] and typeof xm[z] would fail with an error if xm did not exist.我创建这个也是因为我传递给它的对象可能是 x , xm , xm[z] 和 typeof xm[z] 如果 xm 不存在,则会失败并出现错误。

I hope it helps.我希望它有帮助。 (BTW, I am novice with JS) (顺便说一句,我是 JS 的新手)

for me this worked for a DOM-object:对我来说,这适用于 DOM 对象:

if(document.getElementsById('IDname').length != 0 ){
   alert("object exist");
}
if (n === Object(n)) {
   // code
}
if (maybeObject !== undefined)
  alert("Got here!");

set Textbox value to one frame to inline frame using div alignmnt tabbed panel.使用 div alignmnt 选项卡式面板将文本框值设置为一帧以嵌入框架。 So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:所以首先,在设置值之前,我们需要使用以下代码检查选定的选项卡式面板框架是否可用:

Javascript Code : 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>

zero and null are implicit pointers.零和空是隐式指针。 If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it.如果您不进行算术、比较或打印“0”以进行筛选,则无需实际键入它。 Its implicit.其隐含。 As in implied.正如暗示的那样。 Typeof is also not required for the same reason.出于同样的原因,也不需要 Typeof。 Watch.手表。

if(obj) console.log("exists"); if(obj) console.log("exists");

I didn't see request for a not or else there for it is not included as.我没有看到不要求,否则就没有包括在内。 As much as i love extra content which doesn't fit into the question.尽管我喜欢不适合问题的额外内容。 Lets keep it simple.让我们保持简单。

Think it's easiest like this认为这样最简单

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

Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible.或者,你们都可以开始使用我独有的exists()方法,并能够做被认为不可能的事情。 ie: IE:

Things like: exists("blabla") , or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...诸如: exists("blabla") ,甚至: exists("foreignObject.guessedProperty.guessNext.propertyNeeded")也是可能的......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM