`!== undefined`和`in`之间的区别

时间:2017-01-10 21:23:28

标签: javascript object

为什么会使用in而不是!== undefined来检查对象是否包含密钥? 例如:

var obj = {};
obj.a !== undefined; // false
'a' in obj; // false

有什么区别?

2 个答案:

答案 0 :(得分:0)

!== undefined检查值是否为undefinedin检查对象是否包含密钥,该值仍为undefined

var obj = {
    a: undefined,
};
obj.a !== undefined; // false
'a' in obj; // true

答案 1 :(得分:0)

根据官方documentation运营商 in 检查给定对象中是否存在指定的属性。
下面的代码说明propertykey

之间存在差异

// define Point object
function Point() {
  this.xPos = 0;
  this.yPos = 0;
}

// Add new property
Object.defineProperty(Point.prototype, "position", {
   get: function() {
     return "X: " + this.xPos + " Y: " + this.yPos;
   },
   set: function(thePoint) {
     var parts = thePoint.split(", ");
     this.xPos = parts[0] || "";
     this.yPos = parts[1] || "";
   }
});

var aPoint = new Point();
aPoint.position= "10, 20";
console.log("Point coordinates " + aPoint.position);
console.log("Point has position: " + ('position' in aPoint));
console.log("Point keys: " + Object.keys(aPoint));