JavaScript 合并/展平数组

我有一个像这样的JavaScript数组:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

我将如何将单独的内部数组合并为一个类似的数组:

["$6", "$12", "$25", ...]

回答:

您可以使用concat合并数组:

var arrays = [

["$6"],

["$12"],

["$25"],

["$25"],

["$18"],

["$22"],

["$10"]

];

var merged = [].concat.apply([], arrays);

console.log(merged);

使用applyof方法concat将仅将第二个参数作为数组,因此最后一行与此相同:

var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);


还有Array.prototype.flat()一种方法(在ES2019中引入)可用于展平阵列,尽管该方法仅在从版本11开始的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);

以上是 JavaScript 合并/展平数组 的全部内容, 来源链接: utcz.com/qa/409428.html

回到顶部