1、使用flat() es6
语法 Array.flat(depth);
depth表示深度 默认1, 使用Infinity可展开任意深度嵌套的数组
2、使用yield* es6 https://www.yuque.com/zhangwujian/js/uk6fcx
function* iterTree(tree){
if(Array.isArray(tree)){
for(let i = 0 ;i<tree.length;i++){
yield* iterTree(tree[i]);
}
}else{
yield tree;
}
}
let arr1 = [1, 2, ['a', 'b', ['中', '文', [1, 2, 3, [11, 21, 31]]]], 3];
for (const x of iterTree(arr1)) {
console.log(x);
}
3、使用while + Array.some() + Array.isArray() + concat + … 展开运算符
function iterTree2(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(iterTree2(arr1));
4、数组的reduce属性
5、使用while + shift + unshift。循环 shift一个数组成员判断是否是数组,是则unshift加入到数组开头,然后继续shift第一个成员,否则push进目标数组。不用递归
var arr1 = [1, 2, [3], [1, 2, 3, [4, [2, 3, 4]]]];
function flatten(input) {
const stack = [...input]; //保证不会破坏原数组
const result = [];
while(stack.length) {
const first = stack.shift();
if(Array.isArray(first)) {
stack.unshift(...first);
} else{
result.push(first);
}
}
return result;
}
flatten(arr1); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
6、如果是纯数字可以使用toString 然后split最后map转换数据类型。详见知乎链接