V. *_*hin 0 javascript ecmascript-6
我们假设我有这种类型的数组:
[ [1, 2], [3, 4] ]
我需要做的是在更高层上获得嵌套元素,使其看起来像:
[1, 2, 3, 4]
我试图以功能方式达到它,所以代码看起来像这样:
const arr = [ [1, 2], [3, 4] ]
const f = Array.from(arr, x => ...x)
Run Code Online (Sandbox Code Playgroud)
但那会出现Unexpected token ...错误.那么这样做的方法是什么?
你可以使用flatArray 的方法:
const inp = [ [1, 2], [3, 4] ];
console.log(inp.flat());Run Code Online (Sandbox Code Playgroud)
在您的情况下,扩展语法不是您可以以这种方式使用的运算符,这就是错误的原因.
正如@MarkMeyer在评论中正确指出的那样,flatEdge和Internet Explorer尚不支持.在这种情况下,您可以寻求解决方案reduce:
const inp = [[1,2], [3,4]];
console.log(inp.reduce((acc, val) => acc.concat(...val), []));Run Code Online (Sandbox Code Playgroud)