Actually, checking for undefined-ness is not an accurate way of testing whether a key exists.
What if the key exists but the value is actually undefined?
实际上,测试未定义这种结果确实不是一个比较精确的检测键是否存在的有效方法。
false, but the key exists!
上面的结果是 false ,但这个键确是存在的。
You should instead use the in operator:
你应该换用 in 操作:
true, regardless of the actual value
结果是 true,不考虑实际值
If you want to check if a key doesn't exist, remember to use parenthesis:
如果你想要检查一个键是否不存在,记得使用取反:
true if "key" doesn't exist in object
如果键存在于这个对象里,那么结果是 true
ERROR! Equivalent to "false in obj"
这个有错!等于 "false in obj"
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:
或者,如jusi你特别想检测一下对象实际的属性(并非继承的属性),那么使用 hasOwnProperty:
true
这个测试的结果是 true