繁体   English   中英

.flat() 不是 function,怎么了?

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

以下代码

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

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

回报

arr.flat不是 function

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

怎么了?

flat方法尚未在常见浏览器中实现(仅 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) );

代码是由Noah Freitas这里获取的,最初实现的目的是在没有指定depth情况下展平数组。

这也可以工作。

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

或者对于较旧的浏览器,

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

您的浏览器不支持Array.flat 下面是实现它的两种方法。

作为函数, depth变量指定input数组结构应该展平的depth (默认为 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,如果您更喜欢arr.flat()语法,请扩展Array.prototype

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

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

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

另一个简单的解决方案是_.flattenDeep()lodash

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()方法相同,并允许在浏览器中有更多的兼容性

您可以将完整数组设置为一个字符串,然后将其拆分。 .toString().split(',')

const array1 = [
  ['one', 'oneTwo'],
  'two',
  'three',
  'four',
]
console.log('a1', array1.toString().split(','),)

const array2 = [
  ...['one', 'oneTwo'].toString().split(','),
  'two',
  'three',
  'four',
]
console.log('a2', array2)

不确定这是否是一个有效的答案,但是在我尝试扁平化数组时,我使用了 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);

尽管我不确定是否会出现任何浏览器兼容问题,但它的作用就像一个魅力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM