forEach
var arr = [0, 2, 4, 6, 8];
var newArr = arr.forEach(function (item, index, arr) {
// console.log(this); // Window{}
// console.log(arr); // [0, 2, 4, 6, 8]
arr[index] = item / 2;
});
// 1. 对数据的操作会改变原数组
console.log(arr); // [0, 1, 2, 3, 4]
// 2. 不会返回新数组
console.log(newArr); // undefined
map
var arr = [0, 2, 4, 6, 8];
var newArr = arr.map(function (item, index, arr) {
// console.log(this); // Window{}
// console.log(arr); // [0, 2, 4, 6, 8]
return item / 2;
})
// 1. 不改变原数组
console.log(arr) // [0, 2, 4, 6, 8]
// 2. 返回新数组
console.log(newArr); // [0, 1, 2, 3, 4]
总结:
forEach | map |
都只能遍历数组 | |
都是循环遍历数组中的每一项 | |
每次执行匿名函数都支持三个参数(item,index,arr) | |
匿名函数的this指向Window | |
不会返回数组 | 生成新数组并返回 |
对数据的操作会改变原数组 | 不改变原数组 |