26.数组API:map和filter

  • 数组的filter方法:将满足条件的元素添加到一个新的数组中,仅有满足条件的元素
1
2
3
4
5
6
7
8
9
10
11
12
let arr = [1, 2, 3, 4, 5];
// 1.数组的filter方法:
// 将满足条件的元素添加到一个新的数组中
/*
let newArray = arr.filter(function
(currentValue, currentIndex, currentArray) {
// console.log(currentValue, currentIndex, currentArray);
if(currentValue % 2 === 0){
return true;
}
});
console.log(newArray); // [2, 4]
  • 数组的map方法:将满足条件的元素映射到一个新的数组中新的数组和原来的数组一样大小,值为undefined,然后满足条件的时候就设置为具体值
1
2
3
4
5
6
7
8
9
10
11
12
// 2.数组的map方法:
// 将满足条件的元素映射到一个新的数组中
/*
let newArray = arr.map
(function (currentValue, currentIndex, currentArray) {
// console.log(currentValue, currentIndex, currentArray);
if(currentValue % 2 === 0){
return currentValue;
}
});
console.log(newArray); // [undefined, 2, undefined, 4, undefined]
*/