1、老方法
var result = []
function unfold(arr){
for(var i=0;i< arr.length;i++){
if(arr[i] instanceof Array) {
unfold(arr[i]);
} else {
result.push(arr[i]);
}
}
}
var arr = [1,3,4,5,[6,[0,1,5],9],[2,5,[1,5]],[5]];
unfold(arr)
2、使用tostring
var c=[1,3,4,5,[6,[0,1,5],9],[2,5,[1,5]],[5]];
var b = c.toString().split(',')
3、使用es6的reduce函数
var arr=[1,3,4,5,[6,[0,1,5],9],[2,5,[1,5]],[5]];
const flatten = arr => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
var result = flatten(arr)
网友评论