阿
阿叶同志
V1
2023/01/29阅读:24主题:默认主题
for, forEach和map的区别
在开发过程中,经常需要对数组进行遍历。我们可以使用 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 的区别
-
中止循环。for 通过 break 关键字来中止循环,forEach 和 map 不可以。 -
跳过此次循环。for 通过 continue 来跳过,forEach 通过 return 跳过,map 不能跳过。 -
返回值。map 返回一个数组,在 map 的回调函数中,不使用 return 返回值的话,会返回 undeifned。for 和 forEach 没有返回值。 -
改变原数组。map 不改变原数组,for 和 forEach 可以改变原数组。 -
代码量。for 的代码量比 forEach 和 map 要多。
作者介绍
阿
阿叶同志
V1