javascript - 如何将一个数组推入另一个数组
问题描述
一个非常基本的问题,但仍在学习。
我有一个一维数组说 = [a,b,c]
。
和另一个二维数组 = [[1,2,3],[4,5,6],[7,8,9]]
。
如何将数组推入二维数组每一行的开头,以便我的数组结果看起来像这样。
[[a,1,2,3],[b,4,5,6],[c,7,8,9]]
.
解决方案
您可以从 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);
推荐阅读
- c# - 是否可以注入绑定为子选项而不是 IConfiguration 的特定配置类
? - tabulator - 将嵌套的制表数据复制到剪贴板
- time-series - 无法使用 HoltWinters 的 statsmodel 获得适当的预测
- java - Tomcat 9.0.13 - 使用 IntelliJ IDEA 运行时出现 404 错误
- python - 音乐游戏程序:我不知道如何授权程序
- database - 查看带有@符号的名称 | 无法进去描述
- perl - 将数组另外映射到 Perl 中的现有哈希
- testing - 随机场景的端到端测试
- java - 如何根据用户从下拉菜单中选择的参数对 Java 对象列表进行排序?
- linux - 无法将正确的文件移动到 mvfiles