Results 1 to 4 of 4

Thread: How do I create and reference an index variable in javascript?

  1. #1
    Join Date
    Mar 2010

    How do I create and reference an index variable in javascript?

    Hi everyone,

    I am wondering what the normal practice of creating an index variable is in javascript. I am wondering because I have just entered learning javascript through jquery. There is some pre-written code I am using to learn by and I am unsure of how their index variable is working in the code.

    Here is the code:
    jQuery(this).find("li").each(function(n) { // <-- I see that 'n' is the index
    jQuery("div#stripTransmitter" + j + " ul").append("<li><a title='" 
     + jQuery(this).find("img").attr("alt") + "' href='#'>"+(n+1)+"<\/a><\/li>"); //<--I'm not sure how n is being interpreted here
    I can see that the index variable is 'n' but when I'm not sure how javascript is using that variable... I come from ActionScript where I would create the index first and set it to 0. Then I know that I'm starting at 0. I don't see where this 'n' is set anywhere until it's just thrown into the function.

    When I output n+1 into html text, I get [object Object]1.

    Thanks for any help!


  2. #2
    Join Date
    Oct 2006
    I would guess that n is the index to each list item in a form
    The code appends a link starting with 1 since zero wouldn't look right,
    but arrays always begin at zero

  3. #3
    Join Date
    Jul 2008
    urbana, il
    n is the name of an argument to the function you use.
    arguments can be anything, so the value is not coming from anywhere you can see.
    it's passed to the function by the .each() method.
    if you poked around the jQuery source code (not recommended), you would see that each passes two arguments: [index, element].

    basically, they took the trouble of creating an index and current element variable for you, and they pass them as arguments each time the function is executed on every element of the selector's return.
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

  4. #4
    Join Date
    Mar 2010
    ah, thanks.. I should have just looked at the jquery documentation rather than assume I knew what the .each() function was doing...

    That makes sense now that you say that.


Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center