开发者社区> 问答> 正文

旋转JavaScript中数组中的元素

我想知道旋转JavaScript数组的最有效方法是什么。

我想出了这个解决方案,其中一个正数n将数组向右旋转,而一个负数n向左(-length < n < length):

Array.prototype.rotateRight = function( n ) { this.unshift( this.splice( n, this.length ) ); } 然后可以使用这种方式:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; months.rotate( new Date().getMonth() ); 正如克里斯托夫在下面的评论中指出的那样,我上面的原始版本有一个缺陷,那就是正确的版本(附加返回值允许链接):

Array.prototype.rotateRight = function( n ) { this.unshift.apply( this, this.splice( n, this.length ) ); return this; } 是否有可能在JavaScript框架中更紧凑和/或更快速的解决方案? 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-09 11:56:06 596 0
1 条回答
写回答
取消 提交回答
  • 类型安全的通用版本,可更改数组:

    Array.prototype.rotate = (function() { // save references to array functions to make lookup faster var push = Array.prototype.push, splice = Array.prototype.splice;

    return function(count) {
        var len = this.length >>> 0, // convert to uint
            count = count >> 0; // convert to int
    
        // convert count to value in range [0, len)
        count = ((count % len) + len) % len;
    
        // use splice.call() instead of this.splice() to make function generic
        push.apply(this, splice.call(this, 0, count));
        return this;
    };
    

    })();

    2020-02-09 11:56:20
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript面向对象的程序设计 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载