www.webdeveloper.com
Results 1 to 3 of 3

Thread: For loop with complex variable

  1. #1
    Join Date
    Aug 2011
    Posts
    2

    For loop with complex variable

    I need to see output as cat,dog,fish,bird what syntax I suppose to use.

    <script>
    a1=cat;
    a2=dog;
    a3=fish;
    a4=bird;
    for (var i = 1;i <= 4; i++){
    document.writeln(ai);
    }
    </script>

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>123</title>
    <style type="text/css">
    body{color:#000;background-color:#fff;font-family:'Bookman Old Style',Georgia,Verdana;font-size:14px;text-align:center;font-weight:bold;margin-top:300px;}
    </style>
    <script type="text/javascript">
    var animals=['cat','dog','fish','bird'];
    window.onload=function(){document.getElementById('output').innerHTML=animals;}
    </script>
    </head>
    <body>
    <div id="output"></div>
    </body>
    </html>

  3. #3
    Join Date
    Sep 2007
    Posts
    317
    Code:
      
    <script type="text/javascript">
    
    // http://www.w3schools.com/jsref/jsref_obj_string.asp
    // http://www.w3schools.com/jsref/jsref_slice_string.asp
    // http://www.w3schools.com/jsref/jsref_eval.asp
    
    var a1 = 'cat';
    var a2 = 'dog';
    var a3 = 'fish';
    var a4 = 'bird';
    var str =  '';
    
    for (var i = 1;i <= 4; i++){
    
    str = str + eval('a'+i) + ','; 
    
    }
    
    alert(str);  // cat,dog,fish,bird, 
    
    str = str.slice(0, str.length-1);
    
    alert(str); // cat,dog,fish,bird 
    
    document.write(str);
    
    </script>

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