Array.prototype.slice.call(arguments)
来源:互联网 发布:java filedialog 编辑:程序博客网 时间:2024/05/16 01:11
我们知道,Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)
如:
1 var a={length:2,0:'first',1:'second'};2 Array.prototype.slice.call(a);// ["first", "second"]3 4 var a={length:2};5 Array.prototype.slice.call(a);// [undefined, undefined]
可能刚开始学习js的童鞋并不是很能理解这句为什么能实现这样的功能。比如我就是一个,所以,来探究一下。
首先,slice有两个用法,一个是String.slice,一个是Array.slice,第一个返回的是字符串,第二个返回的是数组,这里我们看第2个。
Array.prototype.slice.call(arguments)能够将arguments转成数组,那么就是arguments.toArray().slice();到这里,是不是就可以说Array.prototype.slice.call(arguments)的过程就是先将传入进来的第一个参数转为数组,再调用slice?
再看call的用法,如下例子
1 var a = function(){2 console.log(this); // 'littledu'3 console.log(typeof this); // Object4 console.log(this instanceof String); // true5 }6 a.call('littledu');
可以看出,call了后,就把当前函数推入所传参数的作用域中去了,不知道这样说对不对,但反正this就指向了所传进去的对象就肯定的了。
到这里,基本就差不多了,我们可以大胆猜一下slice的内部实现,如下
1 Array.prototype.slice = function(start,end){2 var result = new Array();3 start = start || 0;4 end = end || this.length; //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键5 for(var i = start; i < end; i++){6 result.push(this[i]);7 }8 return result;9 }
大概就是这样吧,理解就行,不深究。
最后,附个转成数组的通用函数
1 var toArray = function(s){ 2 try{ 3 return Array.prototype.slice.call(s); 4 } catch(e){ 5 var arr = []; 6 for(var i = 0,len = s.length; i < len; i++){ 7 //arr.push(s[i]);
arr[i] = s[i]; //据说这样比push快 8 } 9 return arr;10 }11 }
0 0
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- 函数返回值和返回引用是不同的
- “此网页上的某个 Web 部件或 Web 表单控件无法显示或导入。找不到该类型,或该类型未注册为安全类型。”
- 1.2米的百岁大龙虾 被食素妹子救了
- windows 安装搭建 Nginx
- 分布式缓存- Spring中Memcache的使用
- Array.prototype.slice.call(arguments)
- 数据库查询优化
- Spring的AOP
- (原创)iOS tableview系统左滑删除 左滑置顶 自定义左滑事件功能 输入框弹出
- 以后可能会经常用到的gulp插件
- json--eval--VM1423:3 Uncaught SyntaxError: Invalid or unexpected token
- RabbitMQ之入门HelloWorld(Java)
- AndroidTrainingCHS -- 高效显示Bitmap
- Java设计模式(2)创建型:工厂模式(工厂方法模式与抽象工厂模式)