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]); // ?

标签:slice,prototype
0
投稿

猜你喜欢

  • c#获得目标服务器中所有数据库名、表名、列名的实现代码

    2024-01-25 11:20:48
  • 使用base64对图片的二进制进行编码并用ajax进行显示

    2024-05-02 16:18:24
  • Oracle中pivot函数图文实例详解

    2023-07-12 22:13:49
  • python的去重以及数据合并的用法说明

    2023-01-12 07:12:57
  • Python 虚拟环境venv详解

    2021-04-12 03:44:14
  • 详解Python如何获取列表(List)的中位数

    2022-02-01 02:35:37
  • JS原型继承四步曲及原型继承图一览

    2024-06-13 14:56:04
  • 关于PyQt5中QtGui.QImage图片显示问题解析

    2022-05-17 19:59:12
  • Python3.9.1中使用match方法详解

    2023-09-14 09:51:21
  • python使用JSON模块进行数据处理(编码解码)

    2024-01-01 21:52:42
  • 最长用最基本的MSSQL数据库备份与还原

    2024-01-17 18:23:07
  • 一篇文章带你入门Python正则表达式

    2021-11-29 03:00:56
  • 你是真正的用户体验设计者吗? Ⅰ

    2008-03-20 13:42:00
  • Python Scapy随心所欲研究TCP协议栈

    2023-06-10 23:12:29
  • Python字符串、整数、和浮点型数相互转换实例

    2023-09-20 18:05:52
  • python中的turtle库函数简单使用教程

    2022-08-06 23:22:18
  • 详解mysql触发器trigger实例

    2024-01-20 22:28:29
  • 仿vue-cli搭建属于自己的脚手架的方法步骤

    2024-05-21 10:18:09
  • Mysql数据库的导入导出方式(各种情况)

    2024-01-19 15:40:42
  • javascript读取Json数据并分页显示,支持键盘和滚轮翻页

    2010-01-06 13:03:00
  • asp之家 网络编程 m.aspxhome.com