本文最后更新于 2024-12-17T23:24:28+08:00
克隆数组(浅拷贝)
1 2 3 4
| const _arr = [0, 1, 2]; const arr = [..._arr];
console.log(arr);
|
合并数组
1 2 3 4 5
| const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; const arr = [...arr1, ...arr2];
console.log(arr);
|
去重数组
1 2 3
| const arr = [...new Set([0, 1, 1, null, null])];
console.log(arr);
|
混淆数组
1 2 3
| const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - 0.5);
console.log(arr);
|
清空数组
1 2 3 4
| const arr = [0, 1, 2]; arr.length = 0;
console.log(arr);
|
截断数组
1 2 3 4
| const arr = [0, 1, 2]; arr.length = 2;
console.log(arr);
|
交换赋值
1 2 3 4 5
| let a = 0; let b = 1; [a, b] = [b, a];
console.log(a, b);
|
过滤空值
空值:undefined、null、””、0、false、NaN
1 2 3
| const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
console.log(arr);
|
数组首部插入成员
1 2 3 4 5 6
| let arr = [1, 2]; arr.unshift(0); arr = [0].concat(arr); arr = [0, ...arr];
console.log(arr);
|
数组尾部插入成员
1 2 3 4 5 6 7
| let arr = [0, 1]; arr.push(2); arr.concat(2); arr[arr.length] = 2; arr = [...arr, 2];
console.log(arr);
|
统计数组成员个数
1 2 3 4 5 6 7
| const arr = [0, 1, 1, 2, 2, 2]; const count = arr.reduce((t, v) => { t[v] = t[v] ? ++t[v] : 1; return t; }, {});
console.log(count);
|
解构数组成员嵌套
1 2 3 4
| const arr = [0, 1, [2, 3, [4, 5]]]; const [a, b, [c, d, [e, f]]] = arr;
console.log(a, b, c, d, e, f);
|
解构数组成员别名
1 2 3 4
| const arr = [0, 1, 2]; const { 0: a, 1: b, 2: c } = arr;
console.log(a, b, c);
|
解构数组成员默认值
1 2 3 4
| const arr = [0, 1, 2]; const [a, b, c = 3, d = 4] = arr;
console.log(a, b, c, d);
|
获取随机数组成员
1 2 3 4
| const arr = [0, 1, 2, 3, 4, 5]; const randomItem = arr[Math.floor(Math.random() * arr.length)];
console.log(randomItem);
|
创建指定长度数组
1 2 3
| const arr = [...new Array(3).keys()];
console.log(arr);
|
创建指定长度且值相等的数组
1 2 3
| const arr = new Array(3).fill(0);
console.log(arr);
|
JS中的一些数组技巧(一)
http://s1mplecode.com/cc786bc.html