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,表示该属性不可以被遍历,那么该方案就无法判断含有该属性,但一般开发中不会这样增加属性,可考虑使用,同时该方案不可以判断原型链上的属性。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值