JS—数组的forEach( )

75 阅读1分钟

1.用法概述

forEach() 用来替代for循环,对数组里面的每个元素执行相同的操作,会改变原数组,没创建新数组。

2.语法

arr.forEach(callbackFun(item, index, arr) { })

arr.forEach((item, index, arr) => { });

1)参数

callbackFun()——数组中每个元素执行的函数,该函数有三个参数。

item——当前正在处理的数组元素值。

index——当前正在处理的数组元素的下标。

arr——表示forEach()当前正在处理的数组,即数组对象本身。

2)返回值

无返回值,为undefined,该方法会改变原数组。

3.案例用法

const c1 = [1, 2, 3, 4];

// for (let i = 0; i < c1.length; i++) {
//     c1[i] *= 2
// }

c1.forEach((item, index, arr) => arr[index] = item * 2);
console.log(c1);  //[2, 4, 6, 8]