如何在每x个项目中添加数组中的项目? [英] How to add item in array every x items?

查看:54
本文介绍了如何在每x个项目中添加数组中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I add an item every x item in an array? For example I would like to add an item every 10 items in the 3rd position:

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];

推荐答案

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

You could take a while loop and check the length after taking the starting position and the interval length as increment value.

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; }

这篇关于如何在每x个项目中添加数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆