JS中数组对象的遍历方法 forEach() map() 区别及使用

文章目录

方法声明

map() 方法会创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
var new_array = arr.map(callback[, thisArg])
其中的callback:

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

forEach() 方法对数组的每个元素执行一次给定的函数。
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

官网链接

猜你喜欢

转载自blog.csdn.net/m0_54850467/article/details/123643080