不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2023-07-10 23:18:03  修改时间:2024-05-11 04:05:47  分类:前端/Vue/Node.js  编辑

在开发过程中,需要经常判断对象中是否含有某个属性,以下提供三个方案:

1、方案一

const testObj = {
    a: 10,
    c: '123'
};

Object.defineProperty(testObj, 'b', {
    enumerable: false, // 不可遍历
    value: 'abc'
});

hasProperty(obj, key) {
    return key in obj;
}

console.log('增加属性后的对象', testObj); // {a: 10, c: "123", b: "abc"}
console.log('是否包含属性', this.hasProperty(testObj, 'a')); // true
console.log('是否包含属性', this.hasProperty(testObj, 'toString')); // true
console.log('是否包含属性', this.hasProperty(testObj, 'b')); // true

2、方案二

const testObj = {
   a: 10,
   c: '123'
};

Object.defineProperty(testObj, 'b', {
   enumerable: false, // 不可遍历
   value: 'abc'
});

hasProperty(obj, key) {
   return obj.hasOwnProperty(key);
}

console.log('增加属性后的对象', testObj); // {a: 10, c: "123", b: "abc"}
console.log('是否包含属性', this.hasProperty(testObj, 'a')); // true
console.log('是否包含属性', this.hasProperty(testObj, 'toString')); // false
console.log('是否包含属性', this.hasProperty(testObj, 'b')); // true

3、方案三

const testObj = {
   a: 10,
   c: '123'
};

Object.defineProperty(testObj, 'b', {
   enumerable: false, // 不可遍历
   value: 'abc'
});

hasProperty(obj, key) {
   return Object.keys(obj).includes(key);
}

console.log('增加属性后的对象', testObj); // {a: 10, c: "123", b: "abc"}
console.log('是否包含属性', this.hasProperty(testObj, 'a')); // true
console.log('是否包含属性', this.hasProperty(testObj, 'toString')); // false
console.log('是否包含属性', this.hasProperty(testObj, 'b')); // false

结论

根据代码的结果可以看出:

1、方案一是最优的,既可以判断对象自身的属性,还可以判断原型链上的属性,但如果开发中不需要考虑原型链上的属性,可使用方案二,因为遍历原型链,效率上会稍差一些。
2、其次是方案二,其可以判断对象自身的属性,但不可以判断原型链上的属性,如果开发中不需要考虑原型链上的属性,建议使用该方案。
3、对于方案三,其可以判断对象自身的属性,但是有一种情况特殊,如代码所示,如果使用Object.defineProperty增加对象属性,并且将其enumerable设为false,表示该属性不可以被遍历,那么该方案就无法判断含有该属性,但一般开发中不会这样增加属性,可考虑使用,同时该方案不可以判断原型链上的属性。

 

 

摘自:https://blog.csdn.net/cobek/article/details/125400758