如何在自定义模式中切片数组?

时间:2015-01-16 00:12:28

标签: javascript arrays node.js

我有这个数组:

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

感谢advence!

2 个答案:

答案 0 :(得分:3)

此代码应该这样做:

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

答案 1 :(得分:2)

您可以使用简单的for循环来实现它:

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

for (var i = 0, il = x.length - 2; i < il; i++) {
    result.push([x[i], x[i + 1], x[i + 2]]);
}

console.log(result);

编辑: Array.slice()更优雅,但速度要慢得多。根据{{​​3}}测试,在Chrome上它的速度要慢80% - 85%。如果您不需要担心性能,请选择您喜欢的。例如,如果您需要从数组中切割8个元素,那么使用x.slice(i + 8)[x[i], x[i + 1], x[i + 2], x[i + 3], ...]更容易编写和读取。但是,如果性能很重要,那么直接访问可能是更好的选择。