gpt4 book ai didi

javascript - 如何以自定义模式切片数组?

转载 作者:行者123 更新时间:2023-11-30 08:39:27 25 4
gpt4 key购买 nike

我有这个数组:

var x = [1,2,3,4,5,"a","b","c",9,10];

我想将这个数组切成这样的模式:

var x = [[1,2,3],[2,3,4],[3,4,5],[4,5,"a"],[5,"a","b"],["a","b","c"],["b","c",9],["c",9,10]];

我使用了下面的代码并且能够得到 [[1,2,3],[4,5,"a"],["b","c",9],[10, 11,12]] 。但这对我不起作用。我需要获取上面的模式。

var stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var x = ["a", "b", "c"];
var ad_time = 6;
var result = [];

var ad_index = stream.indexOf(ad_time);

if (~ad_index) {
for (var i = 0; i < x.length; i++) {
stream[ad_index + i] = x[i];
}
}

while (stream.length > 0) {
var chunk = stream.splice(0, 3);
result.push(chunk);

}
console.log(JSON.stringify(result));

提前致谢!

最佳答案

这段代码应该做到这一点:

var x = [1,2,3,4,5,"a","b","c",9,10];

var new_array = [];

for (var i = 0; i < x.length - 2; i++) {
new_array.push(x.slice(i, i + 3));
}

关于javascript - 如何以自定义模式切片数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975339/

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