一句話解釋,數組扁平化是指將一個多維數組(含嵌套)變爲一維數組es6
const arr = [1, 2, 3, [4, 5, [6, 7]]];
const flatten = arr.toString().split(',');
console.log(flatten);
複製代碼
優勢:簡單,方便,對原數據沒有影響數組
缺點:最好數組元素全是數字或字符,不會跳過空位bash
const arr = [1, 2, 3, [4, 5, [6, 7]]];
const flatten = arr.join(',').split(',');
console.log(flatten);
複製代碼
優勢和缺點同toStringes5
const arr = [1, 2, 3, [4, 5, [6, 7]]];
const flatten = arr.flat(Infinity);
console.log(flatten);
複製代碼
優勢:會跳過空位,返回新數組,不會修改原數組。spa
缺點:無code
const arr = [1, 2, 3, [4, 5]];
console.log([].concat(...arr));
複製代碼
優勢:簡單,方便string
缺點:只能扁平化一層it
推薦使用es6的flat方法console