对数组的遍历大家最常用的就是for循环,ES5的话也可以使用forEach,ES5具有遍历数组功能的还有map、filter、some、every、reduce、reduceRight等,只不过他们的返回结果不一样。但是使用foreach遍历数组的话,使用break不能中断循环,使用return也不能返回到外层函数。
- for…in :遍历的是对象的属性,并且,它会遍历对象的原型链上的所有可枚举属性。
- for…of :遍历的是对象的值。它仅遍历对象自身的可迭代属性,不包括原型链上的属性。
- forEach 是 JavaScript 数组对象提供的一个迭代方法,用于遍历数组的每个元素并对其执行提供的回调函数,不会改变原数组。
Array.prototype.customProperty = 'custom';
const arr = [1, 2, 3];
for (let key in arr) {
console.log(key); // 输出 0, 1, 2, customProperty(包括原型链上的属性)
}
for (let value of arr) {
console.log(value); // 输出 1, 2, 3(仅包括数组自身的元素)
}
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number, index, array) {
console.log(`Index ${index}: ${number}`);
});
// 输出:
// Index 0: 1
// Index 1: 2
// Index 2: 3
// Index 3: 4
// Index 4: 5