【问题标题】:Javascript Array AlertJavascript 数组警报
【发布时间】:2011-12-16 05:49:38
【问题描述】:

我是 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?使用警报就足够了。
  • 设置数组的提示:一种快捷方式是使用数组文字语法并直接列出值,而不是一次设置一个。像这样:var aCustomers = ["Frank", "Bob", "Kurt", "Tom"];(如果你喜欢,你仍然可以在每个逗号后用换行符格式化它)

标签: javascript arrays popup alert


【解决方案1】:

如果你想把数组看成数组,你可以说

alert(JSON.stringify(aCustomers));

而不是那些document.writes。

http://jsfiddle.net/5b2eb/

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

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

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

【讨论】:

  • alert(aCustomers.join("\n")); SO .join 嗯??哇!!!这非常有用,我刚刚将这个问题添加到我的收藏夹,它非常有用=3 第一次收藏,谢谢=)
猜你喜欢
  • 2016-02-16
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 2010-12-16
  • 2023-04-01
  • 1970-01-01
相关资源
最近更新 更多