如何在每个x项中添加数组中的项目?

时间:2018-01-16 18:57:41

标签: javascript arrays

如何在数组中每x项添加一个项目? 例如,我想在第3个位置每10个项目添加一个项目:

const arr = [1,2];
const result = [1,2, item];

const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
const result = [1,2,item,3,4,5,6,7,8,9,10,11,item,12,13,14,15,16];

3 个答案:

答案 0 :(得分:3)

您可以采用while循环并在将起始位置和间隔长度作为增量值后检查长度。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
    pos = 2;
    interval = 10;
    
while (pos < array.length) {
    array.splice(pos, 0, 'item');
    pos += interval;
}

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

使用arr.splice方法。计算每个第十个元素的索引,如2,12,22 ......

var arr = [];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

供更多参考 How to insert an item into an array at a specific index?

答案 2 :(得分:0)

这是一个不会改变原始数组的选项..只需循环并插入一个新数组。

/**
 * Add an item to an array at a certain frequency starting at a given index
 * @param array arr - the starting array
 * @param mixed item - the item to be inserted into the array
 * @param integer starting = the index at which to begin inserting
 * @param integer frequency - The frequency at which to add the item
 */
function addItemEvery(arr, item, starting, frequency) {
  for (var i = 0, a = []; i < arr.length; i++) {
    a.push(arr[i]);
    if ((i + 1 + starting) % frequency === 0) {
      a.push(item);
      i++;
      if(arr[i]) a.push(arr[i]);
    }
  }
  return a;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
arr = addItemEvery(arr, "item", 2, 3);
console.log(arr);