因为对象将始终具有属性,所以在循环中使用hasOwnProperty
毫无意义吗?
例如:
const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
for (let property in fruits) {
if (fruits.hasOwnProperty(property)) {
console.log(fruits[property]);
}
}
最佳答案
如果您要处理的是一个不能从另一个对象继承的普通对象,例如您问题中的代码,是的,则不需要进行检查。如果要在从另一个继承的对象上进行迭代,将是很有用的。例如:
const fruit = {
isEdible: true
}
const apple = Object.create(fruit);
apple.color = 'green';
for (var property in apple) {
if (apple.hasOwnProperty(property)) {
console.log(apple[property]);
}
}
在这种情况下,需要进行
hasOwnProperty
检查,以确保for..in
仅在console.log
对象上直接循环apple
的属性-否则,还将打印对象apple
继承自的属性(即fruit
):const fruit = {
isEdible: true
}
const apple = Object.create(fruit);
apple.color = 'green';
for (var property in apple) {
console.log(apple[property]);
}
在大多数情况下,最好只使用
Object.keys
(或Object.entries
或Object.values
)来代替,这将直接在对象上遍历属性(忽略继承的属性):const fruit = {
isEdible: true
}
const apple = Object.create(fruit);
apple.color = 'green';
Object.values(apple).forEach((value) => {
console.log(value);
});
对于您的代码,该代码使用的是不继承自另一个对象的普通对象文字(从
Object
除外,后者没有任何可枚举的属性),它没有任何区别-但是功能性Object方法通常比for..in
循环好用(很多linters禁止使用)