.flat() 不是函数,怎么了?

.flat() is not a function, what's wrong?

代码如下

function steamrollArray(arr) {
  // I'm a steamroller, baby
  return arr.flat();
}

steamrollArray([1, [2], [3, [[4]]]]);

returns

arr.flat is not a function

我在 FirefoxChrome v67 中尝试过,结果相同。

怎么了?

flat 方法在常见浏览器中是 not yet implemented(仅 Chrome v69、Firefox Nightly 和 Opera 56)。这是一项实验性功能。因此你还不能使用它

您可能希望拥有自己的 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)
);

代码取自 here by Noah Freitas,最初是为了在没有指定 depth 的情况下展平数组。

不确定这是否是一个有效的答案,但是在我尝试平整数组时,我使用了 ES6 中引入的 destructuring_assignment

// typeScriptArray:Array<Object> = new Array<Object>();
let concatArray = [];

let firstArray = [1,2,3];
let secondArray = [2,3,4];

concatArray.push(...firstArray);
concatArray.push(...secondArray);

console.log(concatArray);

虽然我不确定是否会出现任何浏览器兼容性问题,但它就像一个魅力。

Array.flat 不是您的浏览器 supported。下面是两种实现方式。

作为一个函数,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;
}

作为 Polyfill,扩展 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;
        }
    });
}

使用 lodash 包中的 _.flatten ;)

这个也可以。

let arr = [ [1,2,3], [2,3,4] ];
console.log([].concat(...arr))

或者对于旧版浏览器,

[].concat.apply([], arr);

类似问题,使用 ES6 .reduce() 方法解决:

const flatArr = result.reduce((acc, curr) => acc.concat(curr),[]);

另一个简单的解决方案是在 lodash

_.flattenDeep()

https://lodash.com/docs/4.17.15#flattenDepth

const flatArrays = _.flattenDeep([1, [2], [3, [[4]]]]);

console.log(flatArrays);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

const array = [
  [
    [6, 6],
    [3, 3],
  ],
  [[7, 7, [9]]],
]

function simplifyArray(array) {
  const result = []

  function recursivePushElem(arr) {
    arr.forEach(i => {
      if (Array.isArray(i)) recursivePushElem(i)
      else result.push(i)
    })
  }
  recursivePushElem(array)

  console.log(result)
  return result
}

simplifyArray(array)
var arr=[[1,2],[3,4],[5,6]];
var result=[].concat(...arr);
console.log(result);    //output: [ 1, 2, 3, 4, 5, 6 ]

您可以简单地使用这个 [].concat(...objArrs),它与 flat() 方法的工作原理相同,并且在浏览器中具有更高的兼容性