首页 > 解决方案 > 如何将一个数组推入另一个数组

问题描述

一个非常基本的问题,但仍在学习。

我有一个一维数组说 = [a,b,c]

和另一个二维数组 = [[1,2,3],[4,5,6],[7,8,9]]

如何将数组推入二维数组每一行的开头,以便我的数组结果看起来像这样。

[[a,1,2,3],[b,4,5,6],[c,7,8,9]].

标签: javascript

解决方案


您可以从 2D 数组中迭代每个项目并将 1D 数组值添加到其中。

如需更多帮助,请查看Unshift

var test = ['a', 'b', 'c'];

var tests = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

var index = 0;
tests.map(item => { //Iterate each item from 2D araay
  if (index < test.length) { // Check if we have any item in 1D array to avoid crash
item.unshift(test[index++]); // Unshift each item so you can add value at 0 index.
  }
});

console.log(tests);


推荐阅读