1、对象遍历使用Object.keys比for-in更优秀,性能更好
使用 Object.keys() 替代 for-in 循环。for-in 循环会遍历对象的所有可枚举属性,包括它的原型链上的属性。而 Object.keys() 只返回对象自身的(并且不在原型链上的)所有可枚举属性的名称。如果你不想遍历原型链上的属性,那么 Object.keys() 是更好的选择。
let person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
},
};
let student = {
classNo: 1,
xueke: "yuwen",
};
student.__proto__ = person;
console.log(student);
// 执行本身的次数和原型链上有的雨元素的次数
for (const key in student) {
console.log(key);
if (Object.hasOwnProperty.call(student, key)) {
const element = student[key];
}
}
// 只执行自己的次数
Object.keys(student).forEach((item) => {
console.log(item, "keys");
});