Array.prototype.flatten = function() {
return this.reduce((prev, next) => {
return prev.concat(Array.isArray(next) ? next.flatten(): next);
}, [])
};
Array.prototype.flat = function(newArr=[]) {
for(let item of this) {
Array.isArray(item) ? item.flat(newArr) : newArr.push(item);
}
return newArr;
}
console.log([1, [2, 3], [[4, 5]]].flatten());
console.log([1, [2, 3], [[4, 5]]].flat([]));
将数组扁平化方法加到数组原型链
最新推荐文章于 2024-07-18 11:48:33 发布