Map
返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
按照原始数组元素顺序依次处理元素
不会对空数组进行检测
不会改变原始数组
// currentValue 必须。当前元素的值
// index 可选。当前元素的索引值
// arr 可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
array.Map(function(currentValue, index, arr), thisValue)
let array = [5, 4, 2, 14];
let newArr = array.map((item) => {
return item + 1;
});
console.log(newArr) // [6, 5, 3, 15]
filter
返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
按照原始数组元素顺序依次处理元素
不会对空数组进行检测
不会改变原始数组
// currentValue 必须。当前元素的值
// index 可选。当前元素的索引值
// arr 可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
array.filter(function(currentValue, index, arr), thisValue)
回调函数中返回值,若返回值为true,这个元素保存到新数组中;若返回值为false,则该元素不保存到新数组中;原数组不发生改变。
let array = [5, 4, 2, 14];
let newArr = array.filter((item) => {
return item > 5;
});
console.log(newArr) // [14]
forEach
forEach()方法类似于 map(),传入的函数不需要返回值,并将元素传递给回调函数。
forEach() 对于空数组是不会执行回调函数的。
forEach()不会返回新的数组,总是返回undefined.
// currentValue 必须。当前元素的值
// index 可选。当前元素的索引值
// arr 可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
array.forEach(function(currentValue, index, arr), thisValue)
let array = [5, 4, 2, 14];
let newArr = array.forEach((item,index) => {
console.log(index,item);
});
//0 5
//1 4
//2 2
//3 14