检查 JavaScript 中是否存在对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4186906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if object exists in JavaScript
提问by Yarin
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
没有定义。
回答by JAL
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. typeof always returns a string.
如果已为其分配任何值,包括 null,则 typeof 将返回 undefined 以外的内容。typeof 总是返回一个字符串。
Therefore
所以
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
回答by gblazex
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
. 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. null !== undefined
gives you what you might expect. Please also note, that foo != null
can be an effective way to check if a variable is neither undefined
nor null
. Of course you can be explicit, because it may help readability.
至于@Kevin 的误解,null == undefined
. 这是由于类型强制,这也是 Crockford 不断告诉每个不确定这种事情的人始终使用严格相等运算符===
来测试可能为假值的主要原因。null !== undefined
给你你可能期望的。另请注意,这foo != null
可能是检查变量是否既不是undefined
也不是 的有效方法null
。当然,您可以明确表示,因为这可能有助于提高可读性。
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. Not to mention that typeof null
will also give you object
which is simply wrong.
如果您将问题限制为检查对象是否存在,这typeof o == "object"
可能是一个好主意,除非您不考虑数组对象,因为这也将报告为object
可能让您有点困惑的类型。更何况这typeof null
也会给你带来object
什么是完全错误的。
The primal area where you really should be careful about typeof
, undefined
, null
, unknown
and other misteries are host objects. 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.
太极区,您真的应该小心typeof
,undefined
,null
,unknown
等misteries是主机对象。他们不能被信任。他们几乎可以自由地做他们想做的任何肮脏的事情。因此,请小心使用它们,如果可以,请检查功能,因为这是使用甚至可能不存在的功能的唯一安全方式。
回答by Calvin
You can use:
您可以使用:
if (typeof objectName == 'object') {
//do something
}
回答by superluminary
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) {}
回答by Nikita Rybak
If that's a global object, you can use if (!window.maybeObject)
如果这是一个全局对象,你可以使用 if (!window.maybeObject)
回答by RussellUresti
You could use "typeof".
你可以使用“typeof”。
if(typeof maybeObject != "undefined")
alert("GOT HERE");
回答by Greg Holst
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) : ""
回答by user513365
I used to just do a if(maybeObject)
as the null check in my javascripts.
我曾经if(maybeObject)
在我的javascripts中做空检查。
if(maybeObject){
alert("GOT HERE");
}
So only if maybeObject
- is an object, the alert would be shown.
I have an example in my site.
所以只有当maybeObject
- 是一个对象时,才会显示警报。我的网站上有一个例子。
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes
回答by Facundo Colombier
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!");
}
回答by and-bri
for me this worked for a DOM-object:
对我来说,这适用于 DOM 对象:
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}