Array.prototype.slice.call(arguments)初探

本文详细解释了Array.prototype.slice.call()方法的用途及其在将类数组对象转换为数组中的应用。通过实例展示了如何利用该方法截取参数并讨论了其在实际开发中的常见应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入:在阅读Airbnb的eslint规范时,看到了Array.prototype.slice.call()方法,不太理解为什么这么用。

使用 Array#slice 将类数组对象转换成数组。

function trigger() {

  var args = Array.prototype.slice.call(arguments);

  …

}

Array.prototype.slice剖析

  • Array是javascript的一个类, slice是Array.prototype的一个方法 ,使用方法Array.prototype.slice, slice就是截取,arrayObj.slice(start, [end]) 是截取数组的一部分。
  • call([thisObj[,arg1[arg2[[argN]]]]]) 

thisObj是一个对象的方法 ,arrg1~argN是参数

那么Array.prototype.slice.call(arguments,1);就是把调用方法的参数截取出来。 

如:

 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剖析

先给个例子,这是jqueyFloat插件里的代码:

if (element.data('jDefined')) {

    if (options && typeof options === 'object') {

        methods.update.apply(this, Array.prototype.slice.call(arguments, 1));

    }

} else {

    methods.init.apply(this, Array.prototype.slice.call(arguments, 1));

}

多次用到 Array.prototype.slice.call(arguments, 1),不就是等于 arguments.slice(1) 吗?

因为arguments并不是真正的数组对象,只是与数组类似而已,所以它并没有slice这个方法,而Array.prototype.slice.call(arguments, 1)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法。要是直接写arguments.slice(1)会报错。

typeof arguments==="Object" //而不是 “Array"


原理剖析

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”);


补充: 

将函数的实际参数转换成数组的方法

方法一:var args = Array.prototype.slice.call(arguments);

方法二:var args = [].slice.call(arguments, 0);

方法三:

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;

    }

}


附:http://blog.youkuaiyun.com/i10630226



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值