检查 JavaScript 中对象是否存在
如何在 JavaScript 中验证对象是否存在?
以下有效:
if (!null)
alert("GOT HERE");
但这会引发错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject
未定义。
How do I verify the existence of an object in 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
您可以安全地对未定义的变量使用
typeof
运算符。如果它被赋予了任何值,包括 null,typeof 将返回除 undefined 之外的其他值。 typeof 总是返回一个字符串。
所以
You can safely use the
typeof
operator on undefined variables.If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.
Therefore
这里有很多半真半假的内容,所以我想我把一些事情说得更清楚了。
实际上,您无法准确判断变量是否存在(除非您想将每隔一行包装到 try-catch 块中)。
原因是 Javascript 有这个臭名昭著的值
undefined
,这显然并不意味着该变量未定义,或者它不存在undefined !== not Define
因此,存在的变量和不存在的变量都会向您报告
undefined
类型。至于@Kevin的误解,
null == undefined
。这是由于类型强制,这也是 Crockford 不断告诉每个不确定此类事情的人始终使用严格相等运算符===
来测试可能的虚假值的主要原因。null !== undefined
为您提供了您可能期望的内容。另请注意,foo != null
可以是检查变量是否既不是undefined
也不是null
的有效方法。当然你可以明确一点,因为这可能有助于可读性。如果您将问题限制为检查对象是否存在,
typeof o == "object"
可能是一个好主意,除非您不考虑数组对象,因为这也将被报告为object
的类型可能会让您有点困惑。更不用说typeof null
也会给你object
这完全是错误的。您真正应该注意
typeof
、undefined
、null
、unknown
和其他问题的主要区域是 host对象。他们不值得信任。他们几乎可以自由地做任何他们想做的肮脏的事情。因此,请小心使用它们,如果可以的话请检查其功能,因为这是使用甚至可能不存在的功能的唯一安全方法。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).
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 existundefined !== not defined
So both a variable that exists and another one that doesn't can report you the
undefined
type.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, thatfoo != null
can be an effective way to check if a variable is neitherundefined
nornull
. 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 ofobject
which may leave you a bit confused. Not to mention thattypeof null
will also give youobject
which is simply wrong.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 用于局部变量
您可以使用 typeof 测试局部对象:
window 用于全局变量
您可以通过检查 window 对象来测试全局对象(在全局范围内定义的对象):
Two ways:
typeof for local variables
You can test for a local object using typeof:
window for global variables
You can test for a global object (one defined on the global scope) by inspecting the window object:
您可以使用:
You can use:
如果这是一个全局对象,您可以使用
if (!window.maybeObject)
If that's a global object, you can use
if (!window.maybeObject)
如果您只关心它的存在(是否已声明?),则批准的答案就足够了:
如果您关心它是否具有实际值,您应该添加:
As
typeof( null ) == "object"
例如
bar = { x: 1, y: 2, z: null}
这样你就可以检查它既不是
null
也不是undefined
,由于如果值不存在加上&&
短路,typeof
不会出错,因此您永远不会遇到运行时错误。就我个人而言,我建议在某处添加一个助手 fn (并且我们不要信任
typeof()
):If you care about its existence only ( has it been declared ? ), the approved answer is enough :
If you care about it having an actual value, you should add:
As
typeof( null ) == "object"
e.g.
bar = { x: 1, y: 2, z: null}
this way you check that it's neither
null
orundefined
, and sincetypeof
does not error if value does not exist plus&&
short circuits, you will never get a run-time error.Personally, I'd suggest adding a helper fn somewhere (and let's not trust
typeof()
):您可以使用“typeof”。
You could use "typeof".
我过去只是在 javascript 中执行
if(maybeObject)
作为 null 检查。因此,只有当
maybeObject
- 是一个对象时,才会显示警报。我的网站上有一个例子。
https://sites.google.com/site/javaerrorsandsolutions/home/javascript -动态复选框
I used to just do a
if(maybeObject)
as the null check in my javascripts.So only if
maybeObject
- is an object, the alert would be shown.I have an example in my site.
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes
该线程很久以前就被打开了。我认为同时使用三元运算符是最简单的选择:
The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:
我刚刚测试了上面的
typeOf
示例,但没有一个对我有用,所以我使用了这个:I've just tested the
typeOf
examples from above and none worked for me, so instead I've used this:除了检查对象/变量是否存在之外,您可能还想提供“最坏情况”输出,或者至少将其捕获到警报中,这样就不会被忽视。
检查、提供替代方案和捕获错误的函数示例。
我创建这个也是因为我传递给它的对象可能是 x 、 xm 、 xm[z] ,如果 xm 不存在, typeof xm[z] 将会失败并出现错误。
我希望它有帮助。 (顺便说一句,我是 JS 新手)
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.
I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.
I hope it helps. (BTW, I am novice with JS)
对我来说,这适用于 DOM 对象:
for me this worked for a DOM-object:
您还可以尝试
&&
运算符。在这种情况下,如果键返回任何不是以下值的值:
它将返回
key
,否则它将返回value
。换句话说,如果值是 true (存在),则返回键,否则返回值。
You could also try the
&&
operator.In this case if the key returns any value that is not:
it will return
key
, else it will returnvalue
.In other words if the value is true (exists) it returns key else it returns value.
如果不存在任何键或 obj,则可以使用它
如果需要验证某个键是否存在,这将验证 Obj 是否存在而不存在任何键
if (Object.keys(obj).includes('键'))
You can use for if not exist any key or obj
This verifies if Obj exist without any key, if you need to verify some existence key
if (Object.keys(obj).includes('key'))
使用 divalignmnt 选项卡式面板将文本框值设置为内联框架的一帧。
因此,首先,在设置值之前,我们需要使用以下代码检查所选选项卡式面板框架是否可用:
Javascript 代码:
set Textbox value to one frame to inline frame using div alignmnt tabbed panel.
So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:
Javascript Code :
零和空是隐式指针。如果您不进行算术、比较或将“0”打印到屏幕上,则无需实际键入它。其隐含的。正如暗示的那样。出于同样的原因,也不需要 Typeof。手表。
if(obj) console.log("存在");
我没有看到“不”的请求,因为它不包含在内。尽管我喜欢不符合问题的额外内容。让我们保持简单。
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. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.
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
或者,你们都可以开始使用我独有的 exists() 方法,并能够做一些被认为不可能的事情。即:
诸如:
exists("blabla")
,甚至:exists("foreignObject.guessedProperty.guessNext.propertyNeeded")
也是可能的......Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:
Things like:
exists("blabla")
, or even:exists("foreignObject.guessedProperty.guessNext.propertyNeeded")
are also possible...