zoukankan      html  css  js  c++  java
  • 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;
        }
    }
     
  • 相关阅读:
    【BZOJ1067】【SCOI2007】降雨量(线段树)
    【BZOJ3489】A simple rmq problem(树套树)
    【BZOJ1146】【CTSC2008】网络管理
    【BZOJ3236】【Ahoi2013】作业
    计算几何的一些板
    【BZOJ3173】【Tjoi2013】最长上升子序列(树状数组)
    解决phpmyadmin导入长脚本超时
    make报错make: *** [sapi/cli/php] Error 1
    wampserver配置redis在phpinfo()里面找不到
    阿里云服务器安装Apache环境外网不能访问
  • 原文地址:https://www.cnblogs.com/jing-tian/p/11770447.html
Copyright © 2011-2022 走看看