1. forEach()
语法:
array.forEach(function(currentValue, index, arr), thisValue)
参数
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | 必需。 数组中每个元素需要调用的函数。 函数参数:
| ||||||||
thisValue | 可选。传递给函数的值一般用 "this" 值。 如果这个参数为空, "undefined" 会传递给 "this" 值 |
注意:
forEach()可以不用知道数组的长度,在调用的过程中不能用break,continue,使用 return 语句实现 continue 关键字的效果,跳过某个元素。
var arr = [1, 2, 3, 4, 5];
arr.forEach(function (item) {
if (item === 3) {
return;
}
console.log(item);
});
打印出1245,跳过3
forEach()没有返回值,不改变原数组
2. map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
语法:
array.map(function(currentValue,index,arr), thisValue)
参数:
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
| ||||||||
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
注意:
必须要有返回值,如果不给return,它会返回一个undefined
return 的返回值是什么,相当于给这个新增的数组添加新的值,但它不会影响原数组,只是将原来的数组拷贝了一份,把拷贝的数组项进行更改,支持链式调用
var newarr=arr.map(function(i){
return "hello "+i
});
console.log(newarr)
参考