一、数组拉平
function arrayFlat(arr) { return arr.reduce((pre, cur) => { const temp = Array.isArray(cur) ? arrayFlat(cur) : cur; return pre.concat(temp); }, []); } const result = arrayFlat([1, [2, 3], [4, [5, 6, [8]], 7]]); console.log(result); // 数组拉平 es6 flat // const arr = [1, [2, 3], [4, [5, 6, [8]], 7]]; // // console.log(arr.flat()); // console.log(arr.flat(2)); // console.log(arr.flat(3)); // [1, [2, [3]]].flat(Infinity);
二、打乱数组
// 方法1 function ArrayBreak1(arr) { const $arr = [...arr]; return $arr.sort(() => Math.random() - 0.5); } console.log(ArrayBreak1([1, 2, 3, 4, 5, 6])); // 方法2 function ArrayBreak2(arr) { const $arr = [...arr]; const result = []; while ($arr.length) { const index = Math.floor(Math.random() * $arr.length); result.push($arr[index]); $arr.splice(index, 1); } return result; } console.log(ArrayBreak2([1, 2, 3, 4, 5, 6]));