Iterating through the arguments object

Published Mon, Sep 14 2009 16:02

One of the things you’ll need when you start using JavaScript is iterating through the arguments object. Most of the time, you’ll probably see code which looks like this:

function iterate1() {
    for (var i = 0; i < arguments.length;  i++) {
        alert(i + ":" + arguments[i]);
    }
}

The previous snippet is simple and lets you iterate over each element. Unfortunately, it won’t work if, for instance, you’re passing it to another function which uses a for…in statement:

function iterate2() {
    for (var aux in arguments) {
        alert(aux + ":" + arguments[aux]);
    }
}

Running the previous sample won’t do anything. If there was an easy way to convert the arguments object into an array…and yes, the answer is that you can easily use your knowledge of the array’s API and contexts to build an array with a single line of BLOCKED SCRIPT

function iterate3() {
    var arr = Array.prototype.slice.call(arguments, 0, arguments.length);
    for (var aux in arr) {
        alert(aux + ":" + arguments[aux]);
    }
}

And there you go! By using the call Function’s method, we’re changing the default context. Notice that we need to pass the first position and the number of elements that should be copied in order to get a “real” array with the parameters that you’ve passed to the function. You can use this trick for transforming any array like object into a “real” array.

And that’s it. Stay tuned for more on JavaScript.

Comments

# Adelihare said on Saturday, October 10, 2009 3:37 PM

Very interesting site. Hope it will always be alive!,

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover