简体   繁体   English

JAVASCRIPT 将数组元素添加到另一个数组迭代

[英]JAVASCRIPT add element of array to another array iterating

I have two arrays:我有两个 arrays:

1) Array 1
[
  ['1', 'a', '1', 'b', '1', 'c', '1', 'd', '1', 'e', ​​'1', 'f', ' 1 ',' g ',' 1 ',' h '],
  ['2', 'a', '2', 'b', '2', 'c', '2', 'd', '2', 'e', ​​'2', 'f', ' 2 ',' g ',' 2 ',' h '],
  ...
]

2) Array 2
[1, 2, 3, 4, 5, 6, 7, 8...]

and now i need add each element of array 2 to the array 1:现在我需要将数组 2 的每个元素添加到数组 1 中:

[
 [
  '1', 1, 'a', '1', 2, 'b', '1', 3, 'c', '1', 4, 'd', '1', 5, 'e', ​​'1', 6, 'f', ' 1 ', 7, ' g ',' 1 ', 8, 'h'
 ], 
 [
  '2', 1, 'a', '2', 2, 'b', '2', 3, 'c', '2', 4, 'd', '2', 5 , 'e', ​​'2', 6, 'f', ' 2 ', 7, ' g ',' 2 ', 8, ' h '
 ],
 ... 
] 

Thanks!谢谢!

If you are trying to merge values from an array to another you might wan't to look at the concat() function.如果您试图将一个数组中的值合并到另一个数组中,您可能不想查看 concat() function。

const array1 = ['a', 'b', 'c'],
      array2 = ['d', 'e', 'f'],
      array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

You can use Array.splice to insert an element at a given position.您可以使用Array.splice在给定的 position 处插入元素。 If I'm not mistaken you want to insert the new elements at every 3th position, starting at 1. So you can define an offset and increase it by 3 after each iteration.如果我没记错的话,您想在每 3 个 position 插入新元素,从 1 开始。因此您可以定义偏移量并在每次迭代后将其增加 3。 Do this for every subelement of the array and you're done.对数组的每个子元素执行此操作,您就完成了。

 let arr = [ ['1', 'a', '1', 'b', '1', 'c', '1', 'd', '1', 'e','1','f', ' 1 ',' g ',' 1 ',' h '], ['2', 'a', '2', 'b', '2', 'c', '2', 'd', '2', 'e','2', 'f', ' 2 ',' g ',' 2 ',' h '] ]; let arr2 = [1, 2, 3, 4, 5, 6, 7, 8]; let offset = 1; for (let i of arr2) { for (let k of arr) { k.splice (offset, 0, String (i)); } offset += 3; } console.log (arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM