The difference and use of the traversal method forEach() map() of array objects in JS

Article directory

method declaration

The map() method creates a new array whose result is that each element in the array is the return value of a single call to the provided function.
var new_array = arr.map(callback[, thisArg])
The callback in it:

function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}

The forEach() method executes the given function once for each element of the array.
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

demo

var arr = [1, 2, 3, 4, 5]

// arr.map(...)会有一个新的数组返回
arr.map(function(element, index, array) {
  return element * 2;
})
// (5) [2, 4, 6, 8, 10]

// arr.forEach() 只是对遍历的每个元素做一些操作(如输出)
arr.forEach(function(element, index, array) {
  console.log(element * 2)
})
// 2
// 4
// 6
// 8
// 10

Official website link

Guess you like

Origin blog.csdn.net/m0_54850467/article/details/123643080
Recommended