为什么会使用in
而不是!== undefined
来检查对象是否包含密钥?
例如:
var obj = {};
obj.a !== undefined; // false
'a' in obj; // false
有什么区别?
答案 0 :(得分:0)
!== undefined
检查值是否为undefined
。 in
检查对象是否包含密钥,该值仍为undefined
:
var obj = {
a: undefined,
};
obj.a !== undefined; // false
'a' in obj; // true
答案 1 :(得分:0)
根据官方documentation运营商 in
检查给定对象中是否存在指定的属性。
下面的代码说明property
和key
:
// 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));