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框架与数组旋转内建吗?(仍未得到任何人的答复)
3 回答

慕码人2483693
TA贡献1860条经验 获得超9个赞
Array.prototype.rotate = function(n) { return this.slice(n, this.length).concat(this.slice(0, n));}
编辑
Array.prototype.rotate = function(n) { while (this.length && n < 0) n += this.length; this.push.apply(this, this.splice(0, n)); return this;}
添加回答
举报
0/150
提交
取消