關(guān)于 Array.prototype.flat
flat 方法會(huì)按照一個(gè)可指定的深度遞歸遍歷數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個(gè)新數(shù)組返回??梢岳斫鉃槎嗑S數(shù)組降維。
語(yǔ)法
var newArray = arr.flat([depth]);
特性
- 參數(shù) depth,指定要提取嵌套數(shù)組的結(jié)構(gòu)深度,默認(rèn)值為 1;
- 參數(shù) depth 為 Infinity,可展開(kāi)任意深度的嵌套數(shù)組;
- 移除數(shù)組中的空項(xiàng)。
代碼實(shí)現(xiàn)
Array.prototype.flat = function(depth) {
// 無(wú)層數(shù),設(shè)置為1
if (depth === undefined) {
depth = 1;
}
// 層數(shù)不是number,返回原數(shù)組
if (typeof depth !== "number" || isNaN(depth)) {
console.error("參數(shù)必須為number");
return this;
}
// 層數(shù)<=0,返回原數(shù)組
if (depth <= 0) {
return this;
}
// 層數(shù)為某個(gè)正整數(shù)時(shí)
function _flat(depth) {
_array = _flatSingle(_array);
depth--;
if (depth > 0) {
_flat(depth);
}
}
// 層數(shù)為正無(wú)窮大時(shí)
function _flatInfinity() {
_array = _flatSingle(_array);
for (let i = 0; i < _array.length; i++) {
if (Array.isArray(_array[i])) {
_flatInfinity();
break;
}
}
}
// 單次降維,同時(shí)過(guò)濾空項(xiàng)
function _flatSingle(array) {
return array.reduce((pre, item) => {
if (Array.isArray(item)) {
item = item.filter(_item => _item !== null);
return [...pre, ...item];
}
item !== null && pre.push(item);
return pre;
}, []);
}
function clone(data) {
return JSON.parse(JSON.stringify(data));
}
let _array = clone(this);
depth === Infinity ? _flatInfinity() : _flat(depth);
return _array;
};
console.log([1, [1, 2]].flat("a")); // [1, [1, 2]]
console.log([1, [1, 2]].flat()); // [1, 1, 2]
console.log([1, [1, [1, 2]]].flat(2)); // [1, 1, 1, 2]
console.log([1, [1, [1, [1, 2]]]].flat(Infinity)); // [1, 1, 1, 1, 2]
console.log([1, [1, 2]].flat(0)); // [1, [1, 2]]
console.log([1, [1, 2]].flat(-2)); // [1, [1, 2]]
console.log([1, , [, 1]].flat()); // [1, 1]
參考文獻(xiàn)
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat