• 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;
        }
    }
     
  • 相关阅读:
    JDBC事务处理
    JDBC之LOB数据类型
    使用JDBC驱动程序处理元数据
    JDBC之PreparedStatement
    JDBC主要API学习总结
    JDBC简介
    ForkJoinPool 分支/合并框架
    线程池
    线程八锁
    jQuery中的事件冒泡
  • 原文地址:https://www.cnblogs.com/jing-tian/p/11770447.html
Copyright © 2020-2023  润新知