1 基本介绍

Array.prototype.slice.call()最常用在把实际参数 转成数组的时候;

比如 Array.prototype.slice.call(arguments,0) ;

是把arguments转为数组。

因为arguments并不是真正的数组对象,只是与数组类似而已,所以它并没有slice这个方法,而Array.prototype.slice.call(arguments, 0)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法。要是直接写arguments.slice(0)会报错。

2.真正原理

Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换) 
如:

  1. var a={length:2,0:'first',1:'second'};//类数组,有length属性,长度为2,第0个是first,第1个是second
  2. console.log(Array.prototype.slice.call(a,0));// ["first", "second"],调用数组的slice(0);
  3. var a={length:2,0:'first',1:'second'};
  4. console.log(Array.prototype.slice.call(a,1));//["second"],调用数组的slice(1);
  5. var a={0:'first',1:'second'};//去掉length属性,返回一个空数组
  6. console.log(Array.prototype.slice.call(a,0));//[]
  7. function test(){
  8. console.log(Array.prototype.slice.call(arguments,0));//["a", "b", "c"],slice(0)
  9. console.log(Array.prototype.slice.call(arguments,1));//["b", "c"],slice(1)
  10. }
  11. test("a","b","c");

3 把参数转为数组的方法总结

方法一:var args = Array.prototype.slice.call(arguments);

方法二:var args = [].slice.call(arguments, 0);

方法三:

  1. var args = [];
  2. for (var i = 1; i < arguments.length; i++) {
  3. args.push(arguments[i]);
  4. }

最后,附个转成数组的通用函数

  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]);
  8. arr[i] = s[i]; //据说这样比push快
  9. }
  10. return arr;
  11. }
  12. }

 

版权声明:本文为yalong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/yalong/p/9214205.html