.flat()不是函数,有什么不对? [英] .flat() is not a function, what's wrong?

查看:137
本文介绍了.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.

您可能希望拥有自己的持平而不是函数:

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)
);

代码取自诺亚,在这里合并一个阵列的数组在这里 Freitas 最初用于在没有指定深度的情况下展平数组。

The code was taken from here by Noah Freitas originally implemented to flatten the array with no depth specified.

这篇关于.flat()不是函数,有什么不对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆