js數組扁平化之簡單方法實現

扁平化

一句話解釋,數組扁平化是指將一個多維數組(含嵌套)變爲一維數組es6

扁平化之es5

toString

const arr = [1, 2, 3, [4, 5, [6, 7]]];

const flatten = arr.toString().split(',');

console.log(flatten);
複製代碼

優勢:簡單,方便,對原數據沒有影響數組

缺點:最好數組元素全是數字或字符,不會跳過空位bash

join

const arr = [1, 2, 3, [4, 5, [6, 7]]];

const flatten = arr.join(',').split(',');

console.log(flatten);
複製代碼

優勢和缺點同toStringes5

扁平化之es6

flat

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

相關文章
相關標籤/搜索