<p>我有一个 JavaScript 数组,例如:</p>
<pre class="brush:php;toolbar:false;">[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]</pre>
<p>我如何将单独的内部数组合并成一个这样的数组:</p>
<pre class="brush:php;toolbar:false;">["$6", "$12", "$25", ...]</pre>
<p><br /></p>
这是一个简短的函数,它使用一些较新的 JavaScript 数组方法来展平 n 维数组。
function flatten(arr) { return arr.reduce(function (flat, toFlatten) { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []); }用法:
ES2019
ES2019 引入了
数组。 prototype.flat()方法,您可以使用它来展平数组。它与大多数环境兼容,尽管它仅在从版本 11 开始的 Node.js 中可用,而不是在 Node.js 中可用。在 Internet Explorer 中完全可以。const arrays = [ ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"] ]; const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. console.log(merge3);