Array.from() 与 Array.reduce()
Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组
Array.reduce()方法对累加器和数组中的每个元素 (从左到右)应用一个函数,将其减少为单个值。
Array.from()
let arrayLike = {
0: "tom",
1: "65",
2: "男",
3: ["jane", "john", "Mary"],
length: 4
};
let arr = Array.from(arrayLike);
console.log(arr);
let arrayLike = {
name: "tom",
age: "65",
sex: "男",
friends: ["jane", "john", "Mary"],
length: 4
};
let arr = Array.from(arrayLike);
console.log(arr);
let arr = [12, 45, 97, 9797, 564, 134, 45642];
let set = new Set(arr);
console.log(Array.from(set));
let arr = [12, 45, 97, 9797, 564, 134, 45642];
let set = new Set(arr);
console.log(Array.from(set, item => item + 1));
let str = "hello world!";
console.log(Array.from(str));
console.log(Array.from([12, 45, 47, 56, 213, 4654, 154]));
Array.reduce()
语法:
array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue);
accumulator:累加器,即函数上一次调用的返回值。第一次的时候为 initialValue || arr[0]
currentValue:数组中函数正在处理的的值。第一次的时候initialValue || arr[1]
currentIndex:数据中正在处理的元素索引,如果提供了 initialValue ,从0开始;否则从1开始
array: 调用 reduce 的数组
initialValue:可选项,累加器的初始值。没有时,累加器第一次的值为currentValue;注意:在对没有设置初始值的空数组调用reduce方法时会报错。
[1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
callback | accumulator | currentValue | currentIndex | array | return value |
---|
first call | 1(数组第一个元素) | 2(数组第二个元素) | 1(无初始值为 1) | [1, 2, 3, 4] | 3 |
second call | 3 | 3 | 2 | [1, 2, 3, 4] | 6 |
third call | 6 | 4 | 3 | [1, 2, 3, 4] | 10 |
[1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
}, 10);
callback | accumulator | currentValue | currentIndex | array | return value |
---|
first call | 10(初始值) | 1(数组第一个元素) | 0(有初始值为 0) | [1, 2, 3, 4] | 11 |
second call | 11 | 2 | 1 | [1, 2, 3, 4] | 13 |
third call | 13 | 3 | 2 | [1, 2, 3, 4] | 16 |
fourth call | 16 | 4 | 3 | [1, 2, 3, 4] | 20 |
[1, 2, 3, 4].reduce((a, b) => a + b);
[[1, 2], [3, 4], [5, 6]]
.reduce((a, b) => a.concat(b), [])
[
(1, 2, 3, 1, 2, 3, 4)
].reduce((items, item) => {
if (item in items) {
items[item]++;
} else {
items[item] = 1;
}
return items;
}, {})
[
(1, 2, 3, 1, 2, 3, 4, 4, 5)
].reduce((init, current) => {
if (init.length === 0 || init.indexOf(current) === -1) {
init.push(current);
}
return init;
}, [])
[
(1, 2, 3, 1, 2, 3, 4, 4, 5)
].sort()
.reduce((init, current) => {
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current);
}
return init;
}, []);