zoukankan      html  css  js  c++  java
  • Array.prototype.slice.call()详解

    slice(start[, end])方法

    概念:通过索引位置获取新的数组,该方法不会修改原数组,返回一个新的子数组,常用于数组的截取

    call(thisArg, arg1, arg2,arg3)方法

    概念:一个对象调用另一个对象的方法,第二个参数为列表列表形式,这是与Apply()第二个参数为数组形式不同的地方

    Array.prototype.slice.call() 能将具有length属性的对象转成数组,比如类数组(arguments,NodeList)、字符串(String)

    Array.prototype.slice.call(arguments, index) 从第index个开始转换成数组,arguments继承了数组的原型方法中的slice方法

    应用场景(一):将函数的实际参数转化为数组

    代码实现

    1、Array.prototype.slice.call(arguments)
    2、[].slice.call(arguments,0)
    3var args = [];
         for(var i=1;i<arguments.length;i++){
             args.push(arguments[i])
         }
     function test(){
           console.log(arguments)//{0:"a",1:"b",2:"c",length:3}
           console.log(Array.prototype.slice.call(arguments));//[a,b,c],将test的实际参数转化为了数组
        };
     test("a","b","c");

    应用场景(二):将字符串,有length属性对象转化为数组,将数字,布尔值,普通对象转化为空数组

    代码实现

    console.log(Array.prototype.slice.call('string')) //["s", "t", "r", "i", "n", "g"]
    console.log(Array.prototype.slice.call(true)) //[]
    console.log(Array.prototype.slice.call(1)) //[]
    console.log(Array.prototype.slice.call({0:'obj'})) //[]
    console.log(Array.prototype.slice.call({0: 'obj1', 1: 'obj2', 2: 'obj3', length: 2}));  // ["obj1", "obj2"]
    
    
  • 相关阅读:
    HDOJ 1241 Oil Deposits【最大连通块 dfs】
    POJ 3984 迷宫问题【迷宫最短路径 bfs】
    封装
    继承的另一种使用方式。。。
    类的绑定方法与继承
    XML模块与类的定义
    常用模块三
    python day19
    常用模块与项目目录规范
    python day17
  • 原文地址:https://www.cnblogs.com/zhangyaolan/p/11157475.html
Copyright © 2011-2022 走看看