javascript 在javascript中向右移动数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16097271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shift array to right in javascript
提问by mike44
I have this array:
我有这个数组:
var arr1 = ['a1', 'a2', 'a3', 'a4', 'a5'];
I need to shift it to right by say 2 locations, like
我需要将它向右移动 2 个位置,例如
arr1 = ['a4', 'a5', 'a1', 'a2', 'a3'];
This works for left shift:
这适用于左移:
arr1 = arr1.concat(arr1.splice(0,2)); // shift left by 2
I get :
我得到:
arr1 = ['a3', 'a4', 'a5', 'a1', 'a2'];
But I don't know how to do shift right...
但我不知道怎么做右移...
回答by zerkms
Shift to right to N
positions == shift to left to array.length - N
positions.
向右移动到N
位置 == 向左移动到array.length - N
位置。
So to shift right on 2 positions for you array - just shift it left on 3 positions.
因此,要为您的阵列右移 2 个位置 - 只需将其左移 3 个位置。
There is no reason to implement another function as soon as you already have one. Plus solutions with shift/unshift/pop
in a loop barely will be as efficient as splice + concat
一旦你已经有了一个功能,就没有理由去实现另一个功能。加上shift/unshift/pop
在循环中的解决方案几乎不会像splice + concat
回答by gilly3
You can use .pop()
to get the last item and .unshift()
to put it at the front:
您可以使用.pop()
获取最后一个项目并将.unshift()
其放在前面:
function shiftArrayToRight(arr, places) {
for (var i = 0; i < places; i++) {
arr.unshift(arr.pop());
}
}
回答by mike44
Using .concat()
you're building a new Array, and replacing the old one. The problem with that is that if you have other references to the Array, they won't be updated, so they'll still hold the unshifted version.
使用.concat()
您正在构建一个新数组,并替换旧数组。问题在于,如果您对 Array 有其他引用,它们将不会更新,因此它们仍将保留未移位的版本。
To do a right shift, and actually mutate the existing Array, you can do this:
要进行右移,并实际改变现有数组,您可以这样做:
arr1.unshift.apply(arr1, arr1.splice(3,2));
The unshift()
method is variadic, and .apply
lets you pass multiple arguments stored in an Array-like collection.
该unshift()
方法是可变参数的,.apply
允许您传递存储在类似数组的集合中的多个参数。
So the .splice()
mutates the Array by removing the last two, and returning them, and .unshift()
mutates the Array by adding the ones returned by .splice()
to the beginning.
因此,.splice()
通过删除最后两个并返回它们来.unshift()
改变数组,并通过将返回的数组添加.splice()
到开头来改变数组。
The left shift would be rewritten similar to the right shift, since .push()
is also variadic:
左移将类似于右移被重写,因为.push()
它也是可变参数:
arr1.push.apply(arr1, arr1.splice(0,2));