我需要编写一个带有两个参数的函数。它将通过弹出一个元素并将其拼接在数组的开头来修改数组。应该重复 num 次。到目前为止我的尝试:
function rotate(arr, num) {
var i = 0;
while (i<num){
arr.pop();
arr.splice(0, 0, arr.pop());
i++;
}
return arr;
}
console.log(rotate(["Harry","Sarah","Oscar","Tina"],2));
最佳答案
Array::pop()
删除并返回删除的元素。您只需使用一次。
正如@Xufox正确提到的
Usually this is done with arr.unshift(arr.pop()); I’m not sure why OP needs to use splice here…
function rotate(arr, num) {
var i = 0;
while (i<num){
arr.unshift(arr.pop());
i++;
}
return arr;
}
console.log(rotate(["Harry","Sarah","Oscar","Tina"],2));
关于javascript - 编写一个使用 .pop 和 .splice 旋转数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45967991/