Array.prototype.slice.call()方法详解

Array.prototype.slice.call()方法详解

翻看很多框架源码,jquery和zepto等等都会有这句话
Array.prototype.slice.call
百思不得其解的我们努力求证……

基本原理

 

  • slice:用来截取截取字符串方法
  • Array: javascript的一个引用类型,其原型prototype上有一个方法叫slice
  • call和apply : 用来改变对象中函数内部的this引用,使得函数可以随便换‘妈妈’
    第一个参数是context(就是上下文的意思),用来替换对象函数中的this
    第二个参数是传递给对象函数的参数

注意这句话对象函数中的this

function test(a,b,c,d) 
   { 
      var arg = Array.prototype.slice.call(arguments,1); 
      alert(arg); 
   } 
   test("a","b","c","d"); //b,c,d

 

疑惑 为什么不直接用 arguments.slice(1)呢 不是一样的么,哈哈

原因 auguments是类数组,不是数组

Array.prototype.slice.call(arguments, 1)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法。要是直接写arguments.slice(1)会报错。

 

 

 
 

 

 

arguments 是object 不是Array ,他的原型上没有slice方法

 
 

 

 

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

var a={length:2,0:'first',1:'second'};//类数组,有length属性,长度为2,第0个是first,第1个是second
console.log(Array.prototype.slice.call(a,0));// ["first", "second"],调用数组的slice(0);

var a={length:2,0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,1));//["second"],调用数组的slice(1);

var a={0:'first',1:'second'};//去掉length属性,返回一个空数组
console.log(Array.prototype.slice.call(a,0));//[]

function test(){
  console.log(Array.prototype.slice.call(arguments,0));//["a", "b", "c"],slice(0)
  console.log(Array.prototype.slice.call(arguments,1));//["b", "c"],slice(1)
}
test("a","b","c");

ps
将函数的实际参数转换成数组的方法

  • 方法一:
    var args = Array.prototype.slice.call(arguments);
  • 方法二:
    var args = Array.prototype.slice.call(arguments);
  • 方法三:
var args = []; 
for (var i = 1; i < arguments.length; i++) { 
    args.push(arguments[i]);
}
  • 方法四 通用方法
var toArray = function(s){
    try{
        return Array.prototype.slice.call(s);
    } catch(e){
        var arr = [];
        for(var i = 0,len = s.length; i < len; i++){
            //arr.push(s[i]);
               arr[i] = s[i];  //据说这样比push快
        }
         return arr;
    }
}
 
posted @ 2019-10-31 12:02  给时光以生命  阅读(1401)  评论(0编辑  收藏  举报