我想知道旋转JavaScript数组的最有效方法是什么.
我想出了这个解决方案,其中正向n旋转数组向右旋转,负向左旋转n(-length < n < length):
Array.prototype.rotateRight = function( n ) {
this.unshift( this.splice( n, this.length ) )
}
Run Code Online (Sandbox Code Playgroud)
然后可以这样使用:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
months.rotate( new Date().getMonth() )
Run Code Online (Sandbox Code Playgroud)
我上面的原始版本有一个缺陷,正如Christoph在下面的评论中指出的那样,正确的版本是(额外的返回允许链接):
Array.prototype.rotateRight = function( n ) {
this.unshift.apply( this, this.splice( n, this.length ) )
return this;
}
Run Code Online (Sandbox Code Playgroud)
是否有更紧凑和/或更快的解决方案,可能在JavaScript框架的上下文中?(以下提出的版本都没有更紧凑或更快)
是否有任何JavaScript框架,内置数组旋转?(还没有人回答)