www.webdeveloper.com
Results 1 to 4 of 4

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

  1. #1
    Join Date
    Mar 2010
    Posts
    3

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

    -B

  2. #2
    Join Date
    Oct 2006
    Posts
    939
    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
    Location
    urbana, il
    Posts
    2,787
    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.

  4. #4
    Join Date
    Mar 2010
    Posts
    3
    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.

    -Brian

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



Recent Articles