How do I shift an array of items up by 4 places in Javascript
How do 开发者_运维问答I shift an array of items up by 4 places in Javascript?
I have the following string array:
var array1 = ["t0","t1","t2","t3","t4","t5"];
I need a function convert "array1" to result in:
// Note how "t0" moves to the fourth position for example
var array2 = ["t3","t4","t5","t0","t1","t2"];
Thanks in advance.
array1 = array1.concat(array1.splice(0,3));
run the following in Firebug to verify
var array1 = ["t0","t1","t2","t3","t4","t5"];
console.log(array1);
array1 = array1.concat(array1.splice(0,3));
console.log(array1);
results in
["t0", "t1", "t2", "t3", "t4", "t5"]
["t3", "t4", "t5", "t0", "t1", "t2"]
You can slice the array and then join it in reversed order:
var array2 = array1.slice(3).concat(array1.slice(0, 3));
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"]
One more way would be this:
var array2 = array1.slice(0);
for (var i = 0; i < 3; i++) {
array2.push(array2.shift());
}
Another way - paste the following code into the large Firebug console to confirm it works:
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(",");
精彩评论