SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Apr 2005
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    looping through variables

    I have variables index1, index2.....index7 and i want to loop thru them like

    for(i=1;i<8;i++)
    {
    if(index..i...>0)
    }

    how will i be able to do it in JS.


    Thanks

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It depends on what type of variables they are

    1) Properties of some object (e.g. form). Use object's name and bracket notation:

    Code:
    o = new Object();
    
    o.a1 = 1
    o.a2 = 2
    o.a3 = 3
    
    for(i = 1; i <= 3; i++)
    	document.write(o["a" + i]);
    2) Global variables, i.e. declared outside any function. They are properties of "window" object, so the technique is the same:

    Code:
    b1 = 1
    b2 = 2
    b3 = 3
    
    for(i = 1; i <= 3; i++)
    	document.write(window["b" + i]);
    3) Local variables, i.e. declared within some function with "var" keyword. The only thing you can do about them is to use eval

    Code:
    function x() {
    	var c1 = 1
    	var c2 = 2
    	var c3 = 3
    
    	for(i = 1; i <= 3; i++)
    		document.write(eval("c" + i));
    }
    
    x()
    Hope this helps.


Bookmarks

Posting Permissions

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