我想知道旋转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
类型安全的通用版本,可更改数组:
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;
};
})();
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。