var arr = [1,2,[[[['p',123,[[{},[null]]]]]]],5,[1,[6,[0,[[[null]]]]]],6,3];
function isArray (arr) {
return Object.prototype.toString.call(arr) == "[object Array]"
}
function flatten (arr) {
var arr = arr || [],
len = arr.length,
resArr = [];
for(var i = 0; i < len; i++) {
if (isArray(arr[i])) {
resArr = resArr.concat(flatten(arr[i]))
} else{
resArr.push(arr[i])
}
}
return resArr
}
数组原型上定义
Array.prototype.flatten = function () {
var resArr = [];
this.forEach(function (item) {
Object.prototype.toString.call(item) == "[object Array]" ? resArr = resArr.concat(item.flatten()) : resArr.push(item);
})
return resArr;
}
用reduce
Array.prototype.flatten2 = function () {
return this.reduce(function (prev,next) {
return Object.prototype.toString.call(next) == "[object Array]" ? prev.concat(next.flatten2()) : prev.concat([next])
},[])
}
function flatten2 (arr) {
var arr = arr || [];
return arr.reduce(function (prev,next) {
return Object.prototype.toString.call(next) == "[object Array]" ? prev.concat(flatten2(next)) : prev.concat([next])
},[])
}
上面要注意, 不能用prev.push(next) 代替 prev.concat([next])
原因是 prev.push(next) 语句执行后的返回值是 next 将会赋值给prev
es6简化
const flatten3 = (arr=[]) => arr.reduce((prev,next) => Object.prototype.toString.call(next) == "[object Array]" ? prev.concat(flatten3(next)) : prev.concat([next]),[])
网友评论