Programming

Turning JavaScript's arguments object into an array

steloflute 2013. 6. 1. 12:56

http://debuggable.com/posts/turning-javascript-s-arguments-object-into-an-array:4ac50ef8-3bd0-4a2d-8c2e-535ccbdd56cb

 

JavaScript is awesome when you stick to the good parts. But sometimes you have to touch it's bad parts. Consider this:

function hello() {
    arguments.unshift('hello');
    alert(arguments.join(' '));
}

hello('pretty', 'world');

"TypeError: arguments. unshift is not a function"! How dare you JavaScript?

JavaScript might trick you into thinking the arguments variable is an array because you can access it like one (arguments[0], arguments[1], ...), but it's lying. The truth is that the arguments variable really is an object.

Lucky for us, the good parts of JavaScript come to rescue, namely prototypical inheritance:

 

function hello() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('hello');
    alert(args.join(' '));
}

hello('pretty', 'world');

This creates a variable called args that holds a true array version of the arguments variable. This works by hjacking the Array.splice function to make it work on the arguments variable.

Yes, this is the kind of code you might want to document for the poor kids who will have to debug grandpa's "AJAX museum" one day.

Got a better solution? Let me know!

-- Felix Geisendörfer aka the_undefined

 

 

'Programming' 카테고리의 다른 글

HTML <textarea> readonly Attribute  (0) 2013.06.10
My favorite regex of all time  (0) 2013.06.04
Building LISP  (0) 2013.05.27
Curried Functions in C  (0) 2013.05.14
(C) perror - print a system error message  (0) 2013.05.08