JavaScript 数组警告

26

我是Javascript的新手。

我正在尝试编写这四个按钮。我目前在第二个按钮上。我已经编写了一个数组。但是当我点击按钮时,它会替换页面。我想在警告框中显示该数组。

<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>

如果你需要在警告框中显示一个数组,那么为什么要使用document.write?使用alert就足够了。 - Kiran
设置数组的技巧:一种快捷方式是使用数组字面量语法,直接列出值,而不是逐个设置。像这样:var aCustomers = ["Frank", "Bob", "Kurt", "Tom"];(如果你喜欢,仍然可以在每个逗号后换行格式化)。 - nnnnnn
https://dev59.com/-HA75IYBdhLWcg3w9-Ox - trante
1个回答

77

如果您想将该数组显示为数组,可以使用以下语句:

alert(JSON.stringify(aCustomers));

不要使用所有这些 document.write

http://jsfiddle.net/5b2eb/

但是,如果您想在弹出窗口中干净地每行显示它们,请执行以下操作:

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

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


1
警告(aCustomers.join("\n")); SO .join 呀??哇!!!这太不可思议了,我刚刚把这个问题添加到我的收藏夹中,它非常有用=3,感谢您的第一个收藏夹 =) - Metafaniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接