JavaScriptArray旋转()

JavaScriptArray旋转()

我在想,最有效的旋转方法是什么?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框架的上下文中?(下面提出的任何版本要么更紧凑,要么更快)

有任何JavaScript框架与数组旋转内建吗?(仍未得到任何人的答复)


胡说叔叔
浏览 300回答 3
3回答

慕码人2483693

我可能会这样做:Array.prototype.rotate&nbsp;=&nbsp;function(n)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this.slice(n,&nbsp;this.length).concat(this.slice(0,&nbsp;n));}编辑以下是变形人版本:Array.prototype.rotate&nbsp;=&nbsp;function(n)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;(this.length&nbsp;&&&nbsp;n&nbsp;<&nbsp;0)&nbsp;n&nbsp;+=&nbsp;this.length; &nbsp;&nbsp;&nbsp;&nbsp;this.push.apply(this,&nbsp;this.splice(0,&nbsp;n)); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript