如何在Javascript中将项目数组向上移动4个位置

时间:2009-10-05 16:29:34

标签: javascript arrays shift

如何在Javascript中将项目数组向上移动4个位置?

我有以下字符串数组:

var array1 = ["t0","t1","t2","t3","t4","t5"];

我需要一个函数转换“array1”导致:

// Note how "t0" moves to the fourth position for example
var array2 = ["t3","t4","t5","t0","t1","t2"];  

提前致谢。

5 个答案:

答案 0 :(得分:27)

array1 = array1.concat(array1.splice(0,3));

在Firebug中运行以下内容以验证

var array1 = ["t0","t1","t2","t3","t4","t5"];
console.log(array1);
array1 = array1.concat(array1.splice(0,3));
console.log(array1);

结果

["t0", "t1", "t2", "t3", "t4", "t5"]
["t3", "t4", "t5", "t0", "t1", "t2"]

答案 1 :(得分:12)

您可以slice数组,然后join按相反的顺序排列:

var array2 = array1.slice(3).concat(array1.slice(0, 3));

答案 2 :(得分:2)

另一种方式是:

var array2 = array1.slice(0);

for (var i = 0; i < 3; i++) {
    array2.push(array2.shift());
}

答案 3 :(得分:2)

function shiftArray(theArray, times) {
    // roll over when longer than length
    times = times % theArray.length;
    var newArray = theArray.slice(times);
    newArray = newArray.concat(theArray.slice(0, times));
    return newArray;
}

var array1 = ["t0","t1","t2","t3","t4","t5"];
var array2 = shiftArray(array1, 3);
alert(array2); // ["t3","t4","t5","t0","t1","t2"]

答案 4 :(得分:0)

另一种方法 - 将以下代码粘贴到大型Firebug控制台中以确认其有效:

var a = [0, 1, 2, 3, 4, 5];
for (var i = 0; i < 3; i++) {
    a.unshift(a.pop());
}
// the next line is to show it in the Firebug console; variable "a" holds the array
a.toString(",");