将数组展平为 1 行

Flatten array to 1 line

嘿,我需要一些帮助 javascript

[ [ 0, 0, 0, -8.5, 28, 8.5 ],
  [ 1, 1, -3, 0, 3, 12 ],
  [ 2, 2, -0.5, 0, 0.5, 5.333333333333333 ] ]

我希望上面的数组采用这种形式

 0 0 0 -8.5 28 8.5, 1 1 -3 0 3 12, 2 2 -0.5 0 0.5 5.333333333333333

concat 和 reduce 在每个值后放置一个逗号

arr.map(item => item.join(' ')).join(',');

您可以简单地使用 Array.prototype.map() & Array.prototype.join()

示例:

var myArr = [ [ 0, 0, 0, -8.5, 28, 8.5 ],
  [ 1, 1, -3, 0, 3, 12 ],
  [ 2, 2, -0.5, 0, 0.5, 5.333333333333333 ] ];
  
  var str = myArr.map(insideArr => insideArr.join(" ")).join();
  
  console.log(str);

这个问题可以分两步回答。首先,使用带有扩展运算符 (...) 的 Array.prototype.reduce() 高阶函数展平数组。然后,使用 Array.prototype.join() 方法将展平数组转换为数字列表。

const arr = [ [ 0, 0, 0, -8.5, 28, 8.5 ],
  [ 1, 1, -3, 0, 3, 12 ],
  [ 2, 2, -0.5, 0, 0.5, 5.333333333333333 ] ];

const flatten = arr.reduce((combine, item) => [...combine, ...item], [])
                   .join(' ');