1.every和some
every表示数组中的每一项都必须通过才会返回true
some表示只要数组元素某一项满足即可
var arr = [1, 2, 3, 4, 5, 6, 7,8, 9];
var a = arr.every(item=> item > 6);
console.log(a); // false
var b = arr.some(item=> item > 6);
console.log(b); // true
2.map() - 映射
var newArr = array.map((currentValue, index, array) => { return ... }, thisValue);
currentValue, 必须,当前的元素值;
index, 可选,当前元素值的索引;
array, 可选,原数组;
thisValue, 可选,对象作为该执行回调时使用,传递给函数,用作 “this” 的值;
return 新数组
var array1 = [1,2,3,4];
const map1 = array1.map(x => x *2);
console.log(map1); // [2,8,6,8]
3.filter过滤和筛选
currentValue, 必须,当前的元素值;
index, 可选,当前元素值的索引;
array, 可选,原数组;
thisValue, 可选,对象作为该执行回调时使用,传递给函数,用作 “this” 的值;
return 新数组;
var arr = [1,2,3, 4,5]
var newArr = arr.filter(item => item>3)
console.log(newArr) // [4, 5]
4.reduce - 累计
total, 必须,初始值,第一次循环之后是计算后的返回值;
currentValue, 必须,当前的元素值;
currentIndex, 可选,当前元素值的索引;
array, 可选,原数组;
initialValue, 可选,传递给函数的初始值,即此值会在第一次循环之前赋值给 total;
return 经过处理过的 total
var arr = [1, 2, 3, 4, 5, 6, 7,8, 9];
var res = arr.reduce(function(accumulator, item){
return accumulator + item;
});
console.log(res); //45
统计字符串中每个字符出现的次数
const str = 'aabbbcccc444jjj222'
const obj = {}
Array.from(str).reduce((accumulator, current) => {
current in accumulator ? accumulator[current]++ : accumulator[current] = 1
return accumulator;
}, obj)
console.log(obj)