推荐写法
function hasProperty(obj, key) {
return key in obj
}
错误写法: Object.keys(obj).includes(key)
function hasProperty(obj, key) {
return Object.keys(obj).includes(key);
}
测试:
console.log(hasProperty({ a: 1, b: 2 }, 'aa')); // false
console.log(hasProperty({ a: 1, b: 2 }, 'a')); // true
但如果使用Object.defineProperty 声明了不可遍历属性,则会出现问题。
function hasProperty(obj, key) {
return Object.keys(obj).includes(key);
}
const obj = {
a: 1,
b: 2
}
Object.defineProperty(obj, "c", {
value: 3,
enumerable: false // 不可枚举
})
console.log(hasProperty(obj, 'c')); // false
错误写法:Object.hasOwnProperty
function hasProperty(obj, key) {
return obj.hasOwnProperty(key);
}
const obj = {
a: 1,
b: 2
}
Object.defineProperty(obj, "c", {
value: 3,
enumerable: false
})
console.log(hasProperty(obj, 'c')); // true
这种写法虽然也可以判断不可枚举
的属性,但是如果是原型链
上的属性则不会被判断。
function hasProperty(obj, key) {
return obj.hasOwnProperty(key);
}
const obj = {
a: 1,
b: 2
}
Object.defineProperty(obj, "c", {
value: 3,
enumerable: false
})
console.log(hasProperty(obj, 'toString')); // false