Display Array

I would like to display the elements in my array but it is NOT working. Here’s my code:

<TITLE>Test Input</TITLE>
<script type="text/javascript">

function addtext() {
   var openURL=new Array("http://google.com","http://yahoo.com","http://www.msn.com","http://www.bing.com");

   for (i=0;i<=openURL.length-1;i++){
<body onload="addtext()">

Here’s the ouput:


It should display:


Any comments or suggestions are greatly apprecitated.

The code that displays your variable is actually just outputting a string.


To use variables and strings you’ll have to concatenate them together. for example:

var someVar = "this is the first part " + anotherVariable + " this is the second part";

In this instance you would do it as follows:

 document.writeln('<tr><td>' + openURL[i] + '</td></tr>');

Also, just to dig in to your code a bit further (hope you don’t mind) :wink:

You don’t need to use “new Array()” to instantiate arrays, square brackets will do the job

var anArray = ["item 1", "item 2", "item 3"];

“document.write” and it’s variants are usually poor for performance, if you’re just testing stuff it doesn’t matter too much, but it’s not the best habit to get in to.

When you’re injecting content; where possible, it’s better to inject 1 big chunk than several smaller ones.

You could use innerHTML for example to add content to the page
Let’s say you have a <div id=“test”></div> in your body section somewhere, you could then do something along the following lines:

function addtext() {
   var openURL= ["http://google.com", "http://yahoo.com", "http://www.msn.com", "http://www.bing.com"];
   var htmlStr = '<table>';

   for (i=0;i<=openURL.length-1;i++){
      htmlStr += '<tr><td>' + openURL[i] + '</td></tr>';

   htmlStr += '</table>';
   document.getElementById("test").innerHTML = htmlStr;

How would I put my array into the window.open() function

document.writeln('<tr><td> <a href = "" onclick="window.open(\\'http://google.com\\'); return false;">'+openURL[i]+'</td></tr></a>'); 

So instead of window.open(\‘http://google.com\’);
I tried window.open(\‘+openURL[i]+\’);

but it does NOT work

When you’re passing in openURL[i] you’ll need to not escape the single quotes. At the moment you’re effectively putting the string “openURL[i]” in window.open.


document.writeln('<tr><td> <a href = "" onclick="window.open('+openURL[i]+'); return false;">'+openURL[i]+'</td></tr></a>');

Should do the trick