Jon*_*eet 2 javascript node.js
例如:
var myObj = {
yes: undefined
}
console.log(typeof myObj.yes === 'undefined') //--> true
console.log(typeof myObj.nop === 'undefined') //--> true too
Run Code Online (Sandbox Code Playgroud)
有没有办法检测myObj.nop是否未定义为undefined?
你会用in:
if('yes' in myObj) {
// then we know the key exists, even if its value is undefined
}
Run Code Online (Sandbox Code Playgroud)
请记住,这也会检查对象原型中的属性,这在您的情况下可能很好,但是如果您只想检查直接在该特定对象上设置的属性,您可以使用Object.prototype.hasOwnProperty:
if(myObj.hasOwnProperty('yes')) {
// then it exists on that object
}
Run Code Online (Sandbox Code Playgroud)
这是关于两者之间差异的好文章.
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |