以下代码
function steamrollArray(arr) {
// I'm a steamroller, baby
return arr.flat();
}
steamrollArray([1, [2], [3, [[4]]]]);返回
arr.flat不是一个函数
我在火狐和Chrome v67上试过,同样的结果也发生了。
怎么了?
发布于 2018-06-22 18:14:16
在普通浏览器中,flat方法是尚未执行 (只有Chrome v69、Firefox和Opera56)。这是一个实验性的特征。因此,你还不能使用它。
您可能希望拥有自己的flat函数:
Object.defineProperty(Array.prototype, 'flat', {
value: function(depth = 1) {
return this.reduce(function (flat, toFlatten) {
return flat.concat((Array.isArray(toFlatten) && (depth>1)) ? toFlatten.flat(depth-1) : toFlatten);
}, []);
}
});
console.log(
[1, [2], [3, [[4]]]].flat(2)
);
发布于 2020-03-13 21:58:36
这也是可行的。
let arr = [ [1,2,3], [2,3,4] ];
console.log([].concat(...arr))或者是旧的浏览器,
[].concat.apply([], arr);发布于 2019-08-29 16:37:21
通过浏览器,Array.flat不是支持。下面是实现它的两种方法。
作为一个函数,depth变量指定input数组结构的深度(默认为1;使用Infinity尽可能深),而stack是扁平数组,在递归调用时通过引用传递,并最终返回。
function flat(input, depth = 1, stack = [])
{
for (let item of input)
{
if (item instanceof Array && depth > 0)
{
flat(item, depth - 1, stack);
}
else {
stack.push(item);
}
}
return stack;
}作为一个多填充,如果您喜欢Array.prototype语法,可以扩展arr.flat():
if (!Array.prototype.flat)
{
Object.defineProperty(Array.prototype, 'flat',
{
value: function(depth = 1, stack = [])
{
for (let item of this)
{
if (item instanceof Array && depth > 0)
{
item.flat(depth - 1, stack);
}
else {
stack.push(item);
}
}
return stack;
}
});
}https://stackoverflow.com/questions/50993498
复制相似问题