The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Writing array names.

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #153973

    list=[“box1″,” box2″, 5];

    for (i=0;i<=list.length;i++);

    I just wanna display the array names on the screen using for loop.


    You are asking too many duplicate questions. I’m beginning to think… troll. Anyways… I’ve posted this for you before…


    for loop syntax looks like this:

    list=["box1"," box2", 5];
    for (i=0;i<=list.length;i++){

    However, this is a bad approach. Arrays have a join method, which can achieve exactly this (but more simply and efficiently):


    Other concerns:

    1 . by using i <= list.length, you’re looping over one more item than exists. (The last thing written will be “undefined”.) Use i < list.length instead.

    2 . The way your code is written, i is a global variable . It doesn’t necessarily cause any problems in this case, but it will eventually. For example, consider what would happen if you decided to put your code in a function and call it five times:

    var list_items = function(){
        for (i=0;i<=list.length;i++){
    for( i=0; i < 5; i++ ){

    i would be 0 on the first Outer loop.

    When your function runs, it will look for the var i, but it doesn’t have one: so it looks in the global scope for i, and finds it.

    i is now set to 0 again, and the function uses it to loop. It gets up to 2 (because there are 3 items in list), the function returns, and your Outer loop continues.

    However, i is now (unexpectedly!) 2. Loop 1 was skipped. Loop 2, however, will be repeated, because i will again be 2 when this next function call is over. This will continue, forever, until the browser literally crashes (or -more likely- the user gives up and kills it).

    When you use such common var names, wrap your code in a function and do var i=0 instead, so they have their own scope and don’t collide with your global var names.

    3 . document.write is not inherently evil, but is tricky. For example, open up a console and type in document.write('what happened to my webpage???')

    It’s more-or-less predictable, but it requires attention to circumstances. Until you have a good handle on it, it is best to avoid making it a habit—it will bite you, one day. What to use instead will depend on exactly what you’re doing – maybe innerHTML, or a library method designed to handle writing to the document (like jQuery’s append).

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.