The difference between forEach, map and filter

forEach():

  • Traverse the array, call each element of the array, and use the callback function to operate on the array, which is essentially equivalent to the for loop.
  • forEach will mutate the original array. no return value,
  • continue and break are not supported
  • return can only jump out of the current loop
// forEach 
// item: 当前元素的值,调用函数必须要有的参数
// index: 当前元素的索引(下标),可选参数
// arrE: 当前元素所属的数组对象,可选参数
let arrE = [1,2,3,4,5]
arrE.forEach((item, index, arrE) => {
    
    
    console.log(index, item, arrE)
})

insert image description here

Note:
When the item is modified, if the item is a value of the original type, the memory address corresponding to the item does not actually change.
If the item is a value of the reference type, the memory address corresponding to the item does not change, but the corresponding value, It has been modified



map()

  • Traverse the array, call each element of the array, and use the callback function to operate on the array, similar to forEach.
  • However, map returns a new array, the original array remains unchanged, and the index structure of the new array is consistent with the original array
  • map needs return return value
//map
// item: 当前元素的值,调用函数必须要有的参数
// index: 当前元素的索引(下标),可选参数
// arrM: 当前元素所属的数组对象,可选参数
let arrM = [4, 9, 16, 25]
let arrMq = arrM.map((item, index, arrM) => {
    
    
    console.log(index, item, arrM)
    return Math.sqrt(item)
})
console.log('------------')
console.log(arrM)
console.log(arrMq)

insert image description here



filter()

  • Traverse the array and return a new array (a subset of the original array), and the callback function is used for logical judgment
  • The callback function is true to add the current element to the new array, false to skip
  • does not change the original array
//filter
// item: 当前元素的值,调用函数必须要有的参数
// index: 当前元素的索引(下标),可选参数
// arrF: 当前元素所属的数组对象,可选参数
let arrF = [1, 2, 3, 4, 5, 4, 2, 3, 6]

// 求偶数
let arrFc = arrF.filter((item, index, arrF) => {
    
    
    console.log(index, item, arrF)
    return item % 2 == 0
})
console.log('----------')
console.log('偶数集合:',arrFc)
console.log('原数组:', arrF)

//数组去重
let arrFs = arrF.filter((item, index) => {
    
    
    //当前元素 在原数组中的第一个索引 === 当前索引值,否则返回当前元素
    return arrF.indexOf(item, 0) === index;
})
console.log('----------')
console.log('数组去重: ', arrFs)
console.log('原数组:', arrF)

insert image description here



The above is my own experience, if there are any mistakes or changes, please suggest

Guess you like

Origin blog.csdn.net/Robergean/article/details/119653744