在箭头函数中返回扩展数组 [英] Return spreaded array in arrow function
问题描述
假设我具有这种类型的数组:
Let's assume i have this type of array:
[[1,2],[3,4]]
我需要做的是在较高层上获取嵌套元素,使其看起来像:
What i need to do is to get nested elements on the higher layer, to make it look like:
[1、2、3、4]
我正在尝试以实用的方式实现这一目标,因此代码看起来像这样:
I am trying to reach that in functional way, so the code look's like this:
const arr = [ [1, 2], [3, 4] ]
const f = Array.from(arr, x => ...x)
但是出现意外令牌...
错误。那么正确的方法是什么?
But that comes up with Unexpected token ...
error. So what's the way to do it right?
推荐答案
您可以使用 flat
数组方法:
const inp = [ [1, 2], [3, 4] ];
console.log(inp.flat());
在您的情况下,扩展语法不是您可以使用的运算符,所以这就是错误的原因。
In your case, the spread syntax is not an operator that you can use in that way, that's why the error.
@MarkMeyer正确指出请注意,Edge和Internet Explorer尚不支持 flat
。在这种情况下,您可以使用 reduce
寻求解决方案:
As @MarkMeyer correctly pointed out in the comments, the flat
is not supported yet by Edge and Internet Explorer. In this case you could go for a solution with reduce
:
const inp = [[1,2], [3,4]];
console.log(inp.reduce((acc, val) => acc.concat(...val), []));
这篇关于在箭头函数中返回扩展数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!