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"]

 

 

 

 


posted @ 2019-07-09 16:10  yaolan  阅读(580)  评论(0编辑  收藏  举报