解构数组成员默认值
const arr = [0, 1, 2];
const [a, b, c = 3, d = 4] = arr;
// a b c d => 0 1 2 4
获取随机数组成员
const arr = [0, 1, 2, 3, 4, 5];
const randomItem = arr[Math.floor(Math.random() * arr.length)];
// randomItem => 1
创建指定长度数组
const arr = [...new Array(3).keys()];
// arr => [0, 1, 2]
创建指定长度且值相等的数组
const arr = new Array(3).fill(0);
// arr => [0, 0, 0]
reduce代替map和filter
const _arr = [0, 1, 2];
// map
const arr = _arr.map(v => v * 2);
const arr = _arr.reduce((t, c) => {
t.push(c * 2);
return t;
}, []);
// arr => [0, 2, 4]
// filter
const arr = _arr.filter(v => v > 0);
const arr = _arr.reduce((t, c) => {
c > 0 && t.push(c);
return t;
}, []);
// arr => [1, 2]
// map和filter
const arr = _arr.map(v => v * 2).filter(v => v > 2);
const arr = _arr.reduce((t, c) => {
c = c * 2;
c > 2 && t.push(c);
return t;
}, []);
// arr => [4]