Array.prototype.slice.call(argments)解读

323 阅读2分钟

基础:

  1. slice()方法可以从已有的数组中返回选定的元素,语法:array.slice(start, end),截取array中第start位到第end位之间的部分,范围:[start, end);
  2. slice()的参数可以省略,省略时默认从0开始,一直到最后一位,也就是返回全部;
  3. call和apply的作用都是在特定作用域中调用函数,例如:程序员.编程.call(外卖员)就是在外卖员作用域中调用程序员的编程方法,即外卖员编程

应用

Array.prototype.slice.call(arguments,[,arg1[arg2]])能将具有length属性的对象转成数组,尤其用于将伪类转换成真正的数组

Array.prototype.slice.call(arrayLike, start, end) 将类数组arrayLike转换为数组,并且从下标start开始到下标为end截取数组

由于slice是数组才拥有的方法,而function中的arguments是类数组,因而argument是无法直接调用调用slice这个方法的,如果尝试去使用如下方法:

function addOne() { 
  return arguments.map(i => i+1); 
}

看上去可行,但是浏览器会报错arguments.map is not a function

这是因为arguments 实际上不是数组,而是类似数组的对象。 可以使用slice实现此功能,如下所示:

function addOne() {
  return Array.prototype.slice.call(arguments).map(i => i+1)
}

Array.prototype.slice.call()能把类数组对象转化成数组,当然像传统的dom对象和js对象都是行不通的,我们接下来举个例子:

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

补充一下

考虑到有一些编译环境可能不支持Array.prototype.slice.call,我们可以考虑将原生方法进行重写,具体代码如下:

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[i] = s[i];
        }
         return arr;
    }
}

引用:理解Array.prototype.slice.call()