遞歸的思想
Array.prototype.flatten = function(){
var temp = [],ary = this;
function fn(ary){
ary.forEach(item=>{
if(typeof item === 'object'){
fn(item);
}else{
temp.push(item);
}
})
}
fn(ary);
return temp;
}
var ary = [1,[2,4],[2,[3,5,6],5],6,7,8]
ary.flatten();//[1, 2, 4, 2, 3, 5, 6, 5, 6, 7, 8]
複製代碼
Array.prototype.flatten = function () {
return [].concat(...this.map(item =>
Array.isArray(item) ? item.flatten() : [item])));
}
複製代碼
數組的toString方法
Array.prototype.flatten = function(){
var ary = this;
ary = ary.toString().split(',').map(item=>+item);
return ary;
}
複製代碼