26

Im new to Javascript.

Im trying to code these four buttons. I'm currently on the second one. I've coded an array. But when I click on the button, it replaces the page. I want to display the array in an alert box.

<html>
<head>
<script type="text/javascript">

function SayHello()
{
    alert("Hello World!");
}

function DumpCustomers()
{

    var aCustomers=new Array();
    aCustomers[0]="Frank Sinatra ";
    aCustomers[1]="Bob Villa ";
    aCustomers[2]="Kurt Cobain ";
    aCustomers[3]="Tom Cruise ";
    aCustomers[4]="Tim Robbins ";
    aCustomers[5]="Santa Claus ";
    aCustomers[6]="Easter Bunny ";
    aCustomers[7]="Clark Kent ";
    aCustomers[8]="Marry Poppins ";
    aCustomers[9]="John Wayne ";

    document.write(aCustomers[0]);
    document.write(aCustomers[1]);
    document.write(aCustomers[2]);
    document.write(aCustomers[3]);
    document.write(aCustomers[4]);
    document.write(aCustomers[5]);
    document.write(aCustomers[6]);
    document.write(aCustomers[7]);
    document.write(aCustomers[8]);
    document.write(aCustomers[9]);
}

function DisplayFishCounts()
{

}
function FindJonGalt()
{

}

</script>
</head>

<body>
<form name="Main">
<input type="button" id=1 onclick="SayHello();" value="Say Hi"/>
<input type="button" id=1 onclick="DumpCustomers();" value="Dump Customers"/>
<input type="button" id=1 onclick="DisplayFishCounts();" value="Display Fish Counts"/>
<input type="button" id=1 onclick="FindJonGalt();" value="Where is Jon Galt?"/>

</form>
</body>
</html>
chrisholdren
  • 281
  • 1
  • 3
  • 5
  • If you need to display an array in alert then why you are using document.write?Use alert its enough. – Kiran Oct 27 '11 at 04:45
  • Tip on setting up arrays: a shortcut is to use array literal syntax and list the values directly rather than setting them one at a time. Like this: `var aCustomers = ["Frank", "Bob", "Kurt", "Tom"];` (if you like you can still format it with a linebreak after each comma) – nnnnnn Oct 27 '11 at 05:34
  • http://stackoverflow.com/questions/3006644/how-i-can-view-array-structure-in-javascript-with-alert – trante Jan 13 '13 at 20:11

1 Answers1

77

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • 1
    `alert(aCustomers.join("\n"));` SO .join huh?? WOW!!! This is so incredible useful I've just add to my Favorites this question, it's so so useful =3 First Fav ever, thanks =) – Metafaniel Jun 06 '12 at 14:54