在 JavaScript 中实现拍平数组,例如:
数组:[1, [2, 3, [4], 5], 6]
输出: [1, 2, 3, 4, 5, 6]
ES6
arr.flat(Infinity);
数组中全为数字
arr.toString().split(',').map(Number)
递归
const myFlat = (arr) => {
const helper = (arr) => {
let res = [];
for (const item of arr) {
if (typeof item === 'object') {
res.push(...item);
} else {
res.push(item);
}
}
return res;
};
while (arr.some(item => typeof item === 'object')) {
arr = helper(arr);
}
return arr;
};
栈代替递归
const myFlat1 = (input) => {
const stack = [...input];
const res = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
res.push(next);
}
}
return res.reverse();
};
正则过滤
function myFlat3(arr) {
let str = JSON.stringify(arr);
// 过滤所有的中中括号
str = str.replace(/(\[|\])/g, '');
str = '[' + str + ']';
return JSON.parse(str);
}
生成器
function* myFlat2(array, depth = 1) {
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
yield* myFlat2(item, depth - 1);
} else {
yield item;
}
}
}