gpt4 book ai didi

javascript - 数组 : how to push all elements forward by one with javascript 中的数组

转载 作者:行者123 更新时间:2023-12-02 06:28:09 25 4
gpt4 key购买 nike

这是我的数组:

arr_1 = [1,2,3]
arr_2 = [4,5,6]
arr_3 = [7,8,9]

arr = [arr_1, arr_2, arr_3]
arr = [[1,2,3], [4,5,6], [7,8,9]]

我想要做的是像这样推送所有元素,以便最终数组如下所示,并在我的数组开头插入另一个元素:

arr = [[i,1,2], [3,4,5], [6,7,8], [9]]

所有子数组不得超过 3 个元素。

感谢您的帮助。

最佳答案

您可以访问所有内部数组并取消移动前一个循环中剩余的值。

var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
chunk = 3,
item = 'x',
i = 0,
temp = [item];

while (i < array.length) {
array[i].unshift(...temp);
temp = array[i].splice(chunk, array[i].length - chunk);
i++;
}
if (temp.length) {
array.push(temp);
}

console.log(array.map(a => a.join(' ')));

关于javascript - 数组 : how to push all elements forward by one with javascript 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com