.flat() 不是函数,有什么问题? [英] .flat() is not a function, what's wrong?
本文介绍了.flat() 不是函数,有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码
function steamrollArray(arr) {
// I'm a steamroller, baby
return arr.flat();
}
steamrollArray([1, [2], [3, [[4]]]]);
返回
arr.flat
不是函数
我在 Firefox 和 Chrome v67 中尝试过,结果相同.
I tried it in Firefox and Chrome v67 and the same result has happened.
怎么了?
推荐答案
flat
方法是 尚未在常见浏览器(仅 Chrome v69、Firefox Nightly 和 Opera 56)中实现.这是一个实验性功能.因此你不能使用它还.
The flat
method is not yet implemented in common browsers (only Chrome v69, Firefox Nightly and Opera 56). It’s an experimental feature. Therefore you cannot use it yet.
您可能希望拥有自己的 flat
函数:
You may want to have your own flat
function instead:
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)
);
代码取自这里,由depth
的情况下展平数组.
The code was taken from here by Noah Freitas originally implemented to flatten the array with no depth
specified.
这篇关于.flat() 不是函数,有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文