(转)Understanding Array.prototype.slice.apply(arguments) in JavaScript

转自:http://blog.sebarmeli.com/2010/11/12/understanding-array-prototype-slice-applyarguments/

If you are a JavaScript developer soon or later you’ll bump into this guy: Array.prototype.slice.apply(arguments) and you’ll ask yourself..what the hell is that??

Well, it’s not that hard to understand actually, it’s just ugly. Anyway, “Array ” is the JS class Array, with “Array.prototype ” you get its prototype. I assume you know about the prototype, the key concept in JavaScript.

slice ” is a method in JavaScript that “selects a part of an array, and returns the new array.” (W3CSchool ). It can have two arguments : start_index(required), end_index.
So given:

var a = ["a", "b", "c"];
a.slice(1,2);

It return ["b"], so an array containing the element between index ’1′ and index ’2′ in the Array “a”.

var a = ["a", "b", "c"];
a.slice(1);

It return ["b", "c"], so an array containing the elements between index ’1′ and last index in the a, which is an Array.

So “a” is an Array of course, what about “arguments ” variable?

Ok, arguments, you know, it’s the implicit JS variable created when you invoke a function, containing the arguments of a function. You’re expecting this variable to be an Array, right?
Well, it’s not, it’s similar, but it’s still an object, so:

function f () {
return arguments;
}

given this function f, launching
f("1", "2") instanceof Array

you’ll get FALSE! That means we can’t apply a bunch of stuff we normally do with an Array, such as push, pop, slice ..but I need those methods, so what can I do?

There you go Array.prototype.slice.apply(arguments) converts arguments into an ARRAY.

Here we use one of the methods to call a function in JavaScript, the APPLY method, you can learn more about how to call a function in JS here .
So we apply the slice function to the first argument of the apply function(in this case “arguments”) and we know that the slice() method returns always an Array. We got our Array!

So now
Array.prototype.slice.apply(f("1", "2")) instanceof Array

it’ll return TRUE!

PS: In ECMAScript5 , we won’t need to use “Array.prototype.slice.apply(arguments)” anymore, but we can easily use arguments.slice() !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值