简体   繁体   English

用于检查对象中属性的存在的“typeof”与“in”

[英]“typeof” versus “in” for checking the presence of a property in an object

I have an object called foo . 我有一个名为foo的对象。 I want to check if it has the property bar . 我想检查它是否有属性bar

Should I use this: 我应该用这个:

if (typeof foo.bar !== "undefined")

Or this: 或这个:

if ("bar" in foo)

Is there any difference? 有什么区别吗?

"typeof" does not care if the property exists or not and it will return undefined even if the property exists but has a value of "undefined" “typeof”并不关心属性是否存在,即使属性存在但值为“undefined”,它也将返回undefined

While, "in" will return true if the property exists and has a value of "undefined" 而如果属性存在且值为“undefined”,则“in”将返回true

For an example, the following would return either true or false depending on which you use: 例如,以下将返回truefalse,具体取决于您使用的是:

let person = {
  name: 'John',
  age: undefined
}

console.log('age' in person)
// true
console.log(typeof person.age !=="undefined") 
//false

Your question is like "which one is the 'best' for checking the presence of a property in an object", therefore the latter ( "bar" in foo ) is what you're looking for. 你的问题就像“检查对象中属性的存在是哪一个'最好'”,因此后者( "bar" in foo )就是你要找的东西。

The result of if("bar" in foo) is "only do this if there's a 'bar' property in foo" which what you're asking for. if("bar" in foo)是“只有if("bar" in foo)有'bar'属性时才执行此操作”,这就是您所要求的。

You could also go for typeof foo.bar != "undefined" but it would be useless overkill. 你也可以去找typeof foo.bar != "undefined"但这样就没用了。

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

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