for…of循环结合Array.prototype.entries()或Array.prototype.keys()或Array.prototype.values()。
以下是一些常用的方法来遍历实体列表(数组):
1. 使用for循环
const entities = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
// ...
];
for (let i = 0; i < entities.length; i++) {
console.log(entities[i].name);
}
2. 使用forEach方法
entities.forEach(entity => {
console.log(entity.name);
});
3. 使用for…of循环
for (const entity of entities) {
console.log(entity.name);
}
4. 使用for…in循环(不推荐用于数组遍历)
虽然for…in循环可以用于遍历数组,但它会遍历数组的所有可枚举属性,包括原型链上的属性,因此通常不推荐用于数组遍历。不过,为了完整性,这里还是给出示例:
for (const key in entities) {
if (entities.hasOwnProperty(key) && !isNaN(key)) { // 检查是否是自身的数字属性
console.log(entities[key].name);
}
}
选择哪种方法取决于你的具体需求和个人偏好。例如,如果你需要基于当前索引执行操作,则for循环或forEach方法可能更合适。如果你只是想简单地遍历数组元素,则for…of循环可能是最清晰的选择。