在循环内移动数组

时间:2015-01-18 17:17:16

标签: javascript arrays node.js

我有一个数组,我想将它移动 n 次并返回一个新的移位数组数组。

如[1,2,3,4]变为

[[ 1, 2, 3, 4 ],
[ 2, 3, 4, 1 ],
[ 3, 4, 1, 2 ],
[ 4, 1, 2, 3 ],
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 1 ],
...

使用

function dataShift(len, inp){
var row = inp;
var rows = [];
for (var i=0;i<len;i++) {
    row.push(row.shift());
    rows.push(row);
    console.log(rows[i]);
}
return rows;
}

console.log(dataShift(5,[1,2,3,4]));

console.log(rows[i])会打印所需的结果,但console.log(dataShift(5,[1,2,3,4]))仅包含原始数组len次的最后一个排列。

我怎样才能达到理想的效果?

2 个答案:

答案 0 :(得分:0)

function dataShift(len, inp){
var row = inp;
var rows = [];
for (var i=0;i<len;i++) {
    row.push(row.shift());
    var new1 = row.slice(0,len);
    rows.push(new1);
}
return rows;
}

console.log(dataShift(5,[1,2,3,4]));

线var new1 = row.slice(0, len)是神奇的地方。 row.slice创建一个新的数组对象。

您之前的方法(直接推送)最终会生成一个指向同一对象的对象引用数组。因此,当您修改对象时,所有引用都会更新。

如果您不想使用slice(),另一种方法是使用JSON.parse(JSON.stringify(row))

答案 1 :(得分:-1)

public static int [] leftSwap(int [] arr, int n) {
        int l = arr.length;
        int [] result = new int[l];
        int  m = 0 ;
        int criticalIndex = l - n ;
        for(int i = 0 ; i <result.length  ; i++) {
            if(i < criticalIndex) {
                result[i] = arr[n];
                n++;
            }

            else {

                result[i] = arr[m];
                        m++;
            }

        }

        return result;
    }