in运算符、Object.hasOwn()、hasOwnProperty()的区别

in运算符

如果指定的属性在指定的对象或其原型链中,则in 运算符返回true

const car = { make: 'Honda', model: 'Accord', year: 1998 };

console.log('make' in car);
// expected output: true

delete car.make;
if ('make' in car === false) {
  car.make = 'Suzuki';
}

console.log(car.make);
// expected output: "Suzuki"

//原型上的属性一样也可以用in 运算符判断是否存在
console.lg('toString' in car)
// expected output: true

Object.hasOwn()与Object.prototype.hasOwnProperty()

如果对象具有指定的属性作为其自己的 属性,则返回true。如果属性被继承或不存在,则该方法返回 false。

// Object.prototype.hasOwnProperty
const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

console.log(object1.hasOwnProperty('toString'));
// expected output: false

console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false

// Object.hasOwn

console.log(Object.hasOwn(object1, 'property1'));
// expected output: true

console.log(Object.hasOwn(object1, 'toString'));
// expected output: false

console.log(Object.hasOwn(object1, 'undeclaredPropertyValue'));
// expected output: false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值