返回

原来 for...of 、forEach、map 遍历数组时不能改变元素!原来是这个原因

前端

前言

for 、for...in 、for...of、forEach、map 五种循环方式看起来只是写法不同,实则本质上还是有区别的,比如我之前遇到的 BUG:

const arr = [1, 2, 3];
for (const item of arr) {
  item += 1;  // Cannot assign to 'item' because it is a constant or read-only.
}
console.log(arr); // [1, 2, 3]

很明显可以看出:for...of 遍历数组时不能改变元素。

一、原理解析

1. for...of

for...of 循环的原理是使用迭代器来遍历数组,迭代器是一个对象,它具有 next() 方法,该方法返回一个包含值和 done 属性的对象。done 属性是一个布尔值,表示迭代是否完成。值属性是迭代器当前指向的元素。

const arr = [1, 2, 3];
for (const item of arr) {
  console.log(item);
}
// 输出:
// 1
// 2
// 3

2. forEach

forEach() 方法也是使用迭代器来遍历数组,但它与 for...of 循环不同的是,forEach() 方法不会返回任何值。forEach() 方法的第一个参数是一个回调函数,该函数将在数组的每个元素上调用。

const arr = [1, 2, 3];
arr.forEach((item) => {
  console.log(item);
});
// 输出:
// 1
// 2
// 3

3. map

map() 方法也是使用迭代器来遍历数组,但它与 for...of 循环和 forEach() 方法不同的是,map() 方法会返回一个新数组,新数组中的每个元素都是通过调用回调函数得到的。

const arr = [1, 2, 3];
const newArr = arr.map((item) => {
  return item + 1;
});
console.log(newArr); // [2, 3, 4]

二、用法区别

1. for...of

for...of 循环适用于需要遍历数组中的每个元素并对每个元素进行操作的情况。

const arr = [1, 2, 3];
for (const item of arr) {
  item += 1;
}
console.log(arr); // [2, 3, 4]

2. forEach

forEach() 方法适用于需要遍历数组中的每个元素并对每个元素执行某个操作的情况。

const arr = [1, 2, 3];
arr.forEach((item) => {
  console.log(item);
});
// 输出:
// 1
// 2
// 3

3. map

map() 方法适用于需要遍历数组中的每个元素并生成一个新数组的情况。

const arr = [1, 2, 3];
const newArr = arr.map((item) => {
  return item + 1;
});
console.log(newArr); // [2, 3, 4]

三、总结

for...of、forEach、map 三种遍历数组的方法各有其特点和用法。在实际开发中,应根据具体情况选择合适的方法。