Javascript - 将定义的变量检测为未定义

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?

Jos*_*eam 5

你会用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)

这是关于两者之间差异的好文章.