- flat()
let arr = [
[1],
[2, 3],
[4, 5, 6, [7, 8, [9, 10, [11]]]],
12
];
// 參數(shù)指要提取嵌套數(shù)組的結(jié)構(gòu)深度,默認值為 1。
// Infinity 指遞歸嵌套的所有層級。
let flattedArr = arr.flat(Infinity);
console.log(flattedArr);
執(zhí)行效果:
- toString()
注意:map()處理空值的問題
console.log(arr.toString().split(',').map(item => Number(item)));
執(zhí)行效果:
- JSON.stringify()
注意:map()處理空值的問題
console.log(JSON.stringify(arr).replace(/\[|\]/g, '').split(',').map(item => Number(item)));
執(zhí)行效果:
- while() {}
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
console.log(arr);
執(zhí)行效果:
- reduce()
對于一個數(shù)組,使用
reduce()
方法遍歷其中的每個元素,如果元素是一個數(shù)組,則遞歸調(diào)用扁平化函數(shù);否則,將元素添加到結(jié)果數(shù)組中。
function flatten(arr) {
return arr.reduce(function (prev, next) {
return prev.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
}
console.log(flatten(arr));
執(zhí)行效果:
- prototype
Array.prototype.myFlat = function () {
let result = [];
let _this = this;
function _flat(arr) {
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (Array.isArray(item)) {
_flat(item);
} else {
result.push(item);
}
}
}
_flat(_this);
return result;
}
console.log(arr.myFlat());
執(zhí)行效果:文章來源:http://www.zghlxwxcb.cn/news/detail-541219.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-541219.html
到了這里,關(guān)于數(shù)組扁平化flat方法的多種實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!