本文介绍了在javascript中将数组右移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组:

var arr1 = ['a1', 'a2', 'a3', 'a4', 'a5'];

我需要将其向右移动2个位置,例如

I need to shift it to right by say 2 locations, like

arr1 = ['a4', 'a5', 'a1', 'a2', 'a3']; 

这适用于左移:

arr1 = arr1.concat(arr1.splice(0,2)); // shift left by 2

我得到了:

arr1 = ['a3', 'a4', 'a5', 'a1', 'a2']; 

但是我不知道该怎么做...

But I don't know how to do shift right...

推荐答案

向右移至 N 个位置==向左移至 array.length-N 个位置.

Shift to right to N positions == shift to left to array.length - N positions.

因此要在数组的2个位置上向右移动-只需在3个位置上向左移动即可.

So to shift right on 2 positions for you array - just shift it left on 3 positions.

已经拥有一个功能就没有理由立即实现.加上在循环中带有 shift/unshift/pop 的解决方案,其效率几乎不及 splice + concat

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

这篇关于在javascript中将数组右移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 11:06