旋转JavaScript中数组中的元素

旋转JavaScript中数组中的元素,第1张

旋转JavaScript中数组中的元素

类型安全的通用版本,可更改数组:

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;    };})();

评论中,Jean提出了代码不支持

push()
and的重载的问题
splice()
。我不认为这真的有用(请参阅评论),但是一种快速的解决方案(虽然有点hack)将替换该行

push.apply(this, splice.call(this, 0, count));

与此:

(this.push || push).apply(this, (this.splice || splice).call(this, 0, count));

在Opera 10中,使用

unshift()
而不是
push()
几乎快一倍,而FF的差异可以忽略不计。编码:

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;    };})();


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5440010.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存