关于程序员:for-forEach和map的区别

6次阅读

共计 1404 个字符,预计需要花费 4 分钟才能阅读完成。

在开发过程中,常常须要对数组进行遍历。咱们能够应用 for, forEach 和 map 来实现对数组的遍历,他们各自有什么特点?让咱们来一探到底。

for

根本应用(以 for..of 为例)

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

个性

1. 能够应用 break 提前终止遍历。

const arr = [1, 2, 3]
for (let item of arr) {if (item > 1) {break}
    console.log(item)
}
// 1

2. 能够应用 continue 来跳过以后的循环。

const arr = [1, 2, 3]
for (let item of arr) {if (item === 2) {continue}
    console.log(item)
}
// 1
// 3

forEach

根本应用

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

个性

1. 不能通过 continue 跳过循环,想跳过循环须要应用 return。

const arr = [1, 2, 3];
arr.forEach((item) => {if (item === 2) {return;}
  console.log(item);
});

2.forEach 没有返回值,返回值为 undefined。

const arr = [1, 2, 3];
let res = arr.forEach((item) => {console.log(item);
  return item
});
console.log(res) // undefined
// 1
// 2
// 3

map

根本应用

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

个性

1. 遍历数组不扭转数组自身。

const arr = [1, 2, 3];
arr.map((item) => {
  // 将每个元素的值减少 1
  item = item + 1
});
console.log(arr) // [1, 2, 3]

2. 有返回值,返回一个新的数组。

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

3. 如需返回元素,必须通过 return,否则返回的元素为 undefined

const arr = [1, 2, 3];
let res = arr.map((item) => {
  // 当元素大于 1 时,返回该元素
  if(item > 1) {return item}
});
console.log(res) // [undefined, 2, 3]

在以上的例子中,在 item 值为 1 时,没有 return 值,所以 map 返回数组的映射(对应)的值为 undefined。

for, forEach 和 map 的区别

  1. 停止循环。for 通过 break 关键字来停止循环,forEach 和 map 不能够。
  2. 跳过此次循环。for 通过 continue 来跳过,forEach 通过 return 跳过,map 不能跳过。
  3. 返回值。map 返回一个数组,在 map 的回调函数中,不应用 return 返回值的话,会返回 undeifned。for 和 forEach 没有返回值。
  4. 扭转原数组。map 不扭转原数组,for 和 forEach 能够扭转原数组。
  5. 代码量。for 的代码量比 forEach 和 map 要多。

本文由 mdnice 多平台公布

正文完
 0