给定一个由不同元素、数组和整数组成的数组,我想得出一个包含该数组中包含的所有整数的数组:
x= [[ 1,2,3], 4, [5,6], 7, 8, [9]]
pretty(x) -> [1,2,3,4,5,6,7,8,9];
我确实设法用一个相当丑陋的缩减来完成它,但我想知道是否有更漂亮的东西可以用它来做:
x.reduce((t, e) => {
if (!e instanceof Array) [e];
return t.concat(e);
});
有什么推荐吗?
谢谢!
最佳答案
使用.flat
:
x= [[ 1,2,3], 4, [5,6], 7, 8, [9]]
x = x.flat(Infinity);
console.log(...x);
x = [[[1, 2, 3]]];
x = x.flat(Infinity);
console.log(...x);
关于javascript - 连接数组和整数的数组的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63566471/