栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

旋转JavaScript中数组中的元素

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464514.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号