JavaScript的数组旋转() [英] JavaScript Array rotate()
问题描述
我想知道什么是旋转的JavaScript 阵列的最有效方法。
I was wondering what was the most efficient way to rotate a JavaScript array.
我想出了这个解决方案,其中正 N
旋转阵列的权利,以及负 N
向左( -length< N<长度
)
I came up with this solution, where a positive n
rotates the array to the right, and a negative n
to the left (-length < n < length
) :
Array.prototype.rotate = function( n ) {
this.unshift( this.splice( n, this.length ) )
}
然后可以这样使用:
Which can then be used this way:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
months.rotate( new Date().getMonth() )
以上我原来的版本有一个缺陷,如克里斯托夫贝娄的评论中指出,正确的版本是(额外的回报允许链接):
My original version above has a flaw, as pointed out by Christoph in the comments bellow, a correct version is (the additional return allows chaining):
Array.prototype.rotate = function( n ) {
this.unshift.apply( this, this.splice( n, this.length ) )
return this;
}
有没有更紧凑和/或更快的解决方案,可能是一个JavaScript框架的背景下? (无建议版本的吼叫或者是更紧凑或更快)。
Is there a more compact and/or faster solution, possibly in the context of a JavaScript framework? (none of the proposed versions bellow is either more compact or faster)
有一个数组旋转内置的JavaScript框架在那里? (仍然没有任何人回答)
Is there any JavaScript framework out there with an array rotate built-in? (Still not answered by anyone)
推荐答案
类型安全,通用版本,变异的数组:
Type-safe, generic version which mutates the array:
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;
};
})();
在的意见,让募集拼接()的问题是,code不支持
。我不认为这是非常有用的(见注释),但一个快速解决方案(一个黑客颇有几分,虽然)将取代行超载推()
和
In the comments, Jean raised the issue that the code doesn't support overloading of push()
and splice()
. I don't think this is really useful (see comments), but a quick solution (somewhat of a hack, though) would be to replace the line
push.apply(this, splice.call(this, 0, count));
这一个:
(this.push || push).apply(this, (this.splice || splice).call(this, 0, count));
使用的unshift()
而不是推()
是接近两倍的速度在Opera 10,而差异在FF可以忽略不计;在code:
Using unshift()
instead of push()
is nearly twice as fast in Opera 10, whereas the differences in FF were negligible; the code:
Array.prototype.rotate = (function() {
var unshift = Array.prototype.unshift,
splice = Array.prototype.splice;
return function(count) {
var len = this.length >>> 0,
count = count >> 0;
unshift.apply(this, splice.call(this, count % len, len));
return this;
};
})();
这篇关于JavaScript的数组旋转()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!