`

(转)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() !

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics