您好,欢迎来到酷升汽车网。
搜索
您的当前位置:首页神奇的rotate函数

神奇的rotate函数

来源:酷升汽车网


我要给大家介绍一种神奇的rotate或者说数组翻转函数,先来看一个例子:

var data = [1, 2, 3, 4, 5];

rotate(data, 1) // => [5, 1, 2, 3, 4]
rotate(data, 2) // => [4, 5, 1, 2, 3]
rotate(data, 3) // => [3, 4, 5, 1, 2]
rotate(data, 4) // => [2, 3, 4, 5, 1]
rotate(data, 5) // => [1, 2, 3, 4, 5]

看出了门道没?没看出没关系,我来说明下。

拿第一个rotate(data,1)来说,相当于第一个到倒数第二的所有元素整体往右边移了一位,而倒数第一的元素划了个半月弧,跑到了第一的位置。

而rotate(data,2)在rotate(data,1)的基础上,执行了相同的操作。

rotate(data,3)在rotate(data,2)的基础上.....

这还没完,rotate函数还有更强大的功能,试着传入个负数,会咋样?

rotate(data, -1) // => [2, 3, 4, 5, 1]
rotate(data, -2) // => [3, 4, 5, 1, 2]
rotate(data, -3) // => [4, 5, 1, 2, 3]
rotate(data, -4) // => [5, 1, 2, 3, 4]
rotate(data, -5) // => [1, 2, 3, 4, 5]


细心的你大概很快就发现了,这是和rotate正数相反的过程。

那如果传入个0,会有什么反应?

rotate(data, 0) // => [1, 2, 3, 4, 5]

翻转0次,不就是什么都不做嘛,汗^_^

这个函数几乎无所不能:

数字数组可以,其它对象数组也可以翻转。

rotate(['a', 'b', 'c'], 1) // => ['c', 'a', 'b']
rotate([1.0, 2.0, 3.0], 1) // => [3.0, 1.0, 2.0]
rotate([true, true, false], 1) // => [false, true, true]

想翻转多少次都没问题!哪怕来个上万次!

var data = [1, 2, 3, 4, 5]

rotate(data, 7) // => [4, 5, 1, 2, 3]
rotate(data, 11) // => [5, 1, 2, 3, 4]
rotate(data, 12478) // => [3, 4, 5, 1, 2]

好了,看了它这么多神奇的特性,咋们来想想该怎么实现它。
既然是分正数,负数和零三种基本情况,那就来个各个击破吧!

对正数,就专门编写这个函数:

if(typeof Array.prototype.shiftRight !== "function"){
 Array.prototype.shiftRight = function(n){
 while(n--){
 this.unshift(this.pop());
 }
 };
}

那么,负数就靠这个功能相反的函数了:

if(typeof Array.prototype.shiftLeft !== "function"){
 Array.prototype.shiftLeft = function(n){
 while(n--){
 this.push(this.shift());
 }
 };
}


最后,就只需要整合下,rotate函数就出来了:

function rotate(array,n){
 //copy array
 array = array.slice(0);
 if(n > 0){
 array.shiftRight(n);
 }
 else if(n < 0){
 array.shiftLeft(-n);
 }
 return array;
}


Copyright © 2019- kushenhuo.cn 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务