我有一个数组
var itemsArr = ["blue", "wine", "orange", "yellow", "cyan"];
如何从数组的END到FRONT获取一定数量的数组元素?
预期产出:
示例1:
//shift final 3 elements
var expected = ["orange", "yellow", "cyan", "blue", "wine"];
示例2:
//shift final 2 elements
var expected = ["yellow", "cyan", "blue", "wine", "orange"];
答案 0 :(得分:3)
这是一种方法:
var a = ["blue", "wine", "orange", "yellow", "cyan"];
function shifter(arr, n) {
var shifted = arr.splice(-n);
return shifted.concat(arr);
}
console.log(shifter(a, 3));
答案 1 :(得分:2)
您可以与Array#splice
和Array#concat
结合使用。
var itemsArr = ["blue", "wine", "orange", "yellow", "cyan"];
itemsArr = itemsArr.splice(-3).concat(itemsArr);
document.write('<pre>' + JSON.stringify(itemsArr, 0, 4) + '</pre>');
itemsArr = itemsArr.splice(3).concat(itemsArr);
document.write('<pre>' + JSON.stringify(itemsArr, 0, 4) + '</pre>');
答案 2 :(得分:1)
function moveToFront(x, noFromEnd){
if(noFromEnd > x.length){
alert("Immpossible");
}
else if(noFromEnd == x.length){
return x;
}
else if(noFromEnd < 0){
alert("immpossible")
}
else if(noFromEnd == 0){
return x;
}
else{
var returnArray = []
for(var i=(x.length-noFromEnd);i<x.length;i++){
returnArray.push(x[i])
}
for(var i=0; i<(x.length-noFromEnd); i++){
returnArray.push(x[i])
}
return returnArray;
}
}