LA.NET [EN]

Sep 14

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 JavaScript:



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.

4 comments so far

  1. Samoys
    6:13 pm - 10-3-2009

    lot about you

  2. Adelihare
    8:37 pm - 10-10-2009

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

  3. Aalidda
    1:08 am - 10-12-2009

    Great work,webmaster,nice design!,

  4. Doctorset
    5:34 pm - 11-20-2009

    This is the welcome page for the dentaldoctor.us Association web site.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>