为什么用foreach,map,find,findIndex

416 阅读1分钟

foreach 和 map 均遍历数组内元素进行操作。

当你需要对原数组操作时用foreach。

当你需要一个新的数组执行别的操作时用map。

find是对数组内元素就行操作,寻找符合条件的第一个数据并返回

findIndex是对数组元素遍历,返回符合条件元素的在数组内的位置

foreach,map,find,findIndex均接受三个参数(item,index,arr)

使用foreach对数组操作

let arr = [1,2,3,4,5]
let res = arr.foreach((item,index,input) => {
	input[index] = item * 10
}).filter((m) =>  m > 10)
console.log(res)			undefined
console.log(arr)			10,20,30,40,50

使用map对数组操作

let arr = [1,2,3,4,5]
let res = arr.map((item,index,input) => {
	return input[index] = item * 10
}).find((m) => m = arr[index])
console.log(res)			10,20,30,40,50
console.log(arr)			1,2,3,4,5