Array.prototype.slice
作者:lifesinger 发布时间:2010-05-07 12:43:00
slice 可以用来获取数组片段,它返回新数组,不会修改原数组。
除了正常用法,slice 经常用来将 array-like 对象转换为 true array.
名词解释:array-like object – 拥有 length 属性的对象,比如 { 0: ‘foo’, length: 1 }, 甚至 { length: ‘bar’ }. 最常见的 array-like 对象是 arguments 和 NodeList.
查看 V8 引擎 array.js 的源码,可以将 slice 的内部实现简化为:
function slice(start, end) { var len = ToUint32(this.length), result = []; for(var i = start; i < end; i++) { result.push(this[i]); } return result;}
可以看出,slice 并不需要 this 为 array 类型,只需要有 length 属性即可。并且 length 属性可以不为 number 类型,当不能转换为数值时,ToUnit32(this.length) 返回 0.
对于标准浏览器,上面已经将 slice 的原理解释清楚了。但是恼人的 ie, 总是给我们添乱子:
var slice = Array.prototype.slice;slice.call(); // => IE: Object expected.slice.call(document.childNodes); // => IE: JScript object expected.
以上代码,在 ie 里报错。可恨 IE 的 Trident 引擎不开源,那我们只有猜测了:
function ie_slice(start, end) { var len = ToUint32(this.length), result = []; if(__typeof__ this !== 'JScript Object') throw 'JScript object expected'; if(this === null) throw 'Oject expected'; for(var i = start; i < end; i++) { result.push(this[i]); } return result;}
至此,把猥琐的 ie 自圆其说完毕。
关于 slice, 还有一个话题:用 Array.prototype.slice 还是 [].slice ? 从理论上讲,[] 需要创建一个数组,性能上会比 Array.prototype 稍差。但实际上,这两者差不多,就如循环里用 i++ 还是 ++i 一样,纯属个人习惯。
最后一个话题,有关性能。对于数组的筛选来说,有一个牺牲色相的写法:
var ret = [];for(var i = start, j = 0; i < end; i++) { ret[j++] = arr[i];}
用空间换时间。去掉 push, 对于大数组来说,性能提升还是比较明显的。
一大早写博,心情不是很好,得留个题目给大家:
var slice = Array.prototype.slice;alert(slice.call({0: 'foo', length: 'bar'})[0]); // ?alert(slice.call(NaN).length); // ?alert(slice.call({0: 'foo', length: '100'})[0]); // ?
猜你喜欢
- 准备导入的excel为: 可以采用pandas的read_excel功能,具体代码如下:import pandas as pdge
- 官方文案:https://docs.python.org/zh-cn/3/library/hashlib.htmlhashlib --- 安
- 在web页面中,图片居左,内容居右排列,是非常常见的效果,它也就是媒体对象,它是一种抽象的样式,可以用来构建不同类型的组件,在bootstr
- 本文为大家分享了python银行管理系统的具体代码,供大家参考,具体内容如下自己写的练手小程序,练习面向对象的概念,代码中都有注释,刚学的同
- 基本设置class Map3D( # 初始化配置项,参考 `global_options.InitOpts` &n
- 这篇论坛文章着重介绍了SQL Server数据库简体繁体数据混用的问题,详细内容请参考下文:我现在要说的是一个在简体繁体数据混用的时候很容易
- 本文实例讲述了PHP封装的PDO数据库操作类。分享给大家供大家参考,具体如下:<?phpclass DatabaseHandler {
- 除了实现新的种类的对象以外,类有时有用于扩展Python的内置类型的功能。主要有以下两种技术:通过嵌入扩展类型下例把一些集合函数变成方法,而
- DateDiff(timeinterval,date1,date2 [, firstdayofweek [, firstweekofyear
- 1. 基础缩略图给a标签添加类class="thumbnail"如下:<div class="
- 在开发难免遇到一些前端需要验证输入的数据是否合法的问题,收集分享在这里同学们使用,欢迎补充。1.标签上直接替换方法:JS 控制不能输入特殊字
- 创建RandomWalk类为模拟随机漫步,我们将创建一个RandomWalk类,随机选择前进方向,这个类有三个属性,一个存储随机漫步的次数,
- 我就废话不多说了,大家还是直接看代码吧!# -*- coding: utf-8 -*-"""Created o
- 1、查看数据库的字符集数据库的字符集必须和Linux下设置的环境变量一致,不然会有乱码。以下两个sql语句都可以查到:select * fr
- 方法一: $(document).on('touchmove',function(e){ e.preventDefault(
- 目录1. Dash2. Pillow3. Colorama4. JmesPath5. Simplejson6. Emoji7. 进度条:pr
- 自从HTML5能为我们的新网页带来更高效洁净的代码而得到更多的关注,然而唯一能让IE识别那些新元素(如<article>)的途径
- 本文实例讲述了Python实现监控程序执行时间并将其写入日志的方法。分享给大家供大家参考。具体实现方法如下:# /usr/bin/pytho
- 描述log10() 方法返回以10为基数的x对数,x>0。语法以下是 log10() 方法的语法:import mathmath.lo
- 阻塞定义当来自应用程序的第一个连接控制锁而第二个连接需要相冲突的锁类型时,将发生阻塞。其结果是强制第二个连接等待,而在第一个连接上阻塞。不管