1

这里的目标是用 Javascript 比较两组随机生成的十个数字,以确定它们是否大于、小于或等于彼此。

到目前为止我有这个:

document.write("Comparing Numbers from Corresponding Lists: <br>");

var list1=new Array();
for(var i=0; i < 10; i++)
{
list1[i]=Math.round(Math.random()*100);
}

var list2=new Array();
for(var i=0; i < 10; i++)
{
list2[i]=Math.round(Math.random()*100);
}

if (list1>list2) {
document.write(list1 + " is greater than " + list2);
} else if (list1<list2) {
document.write(list1 + " is less than " + list2);
} else if (list1=list2) {
document.write(list1 + " is equal to " + list2);
}

这样做是显示以下内容:

Comparing Numbers from Corresponding Lists: 
15,4,30,39,46,8,91,85,64,17 is less than 97,78,32,50,60,36,42,6,12,80

但是我需要它在两列中(比如一个有两列和十行的表)。一位同学建议将 if/else if 语句放在 for() 循环中,但我不确定在 for 后面的括号中放置什么语句;我认为前两个陈述可能是这样的(第三个我不知所措):

for (var list1 = 0, list2 = 0; list1.length, list2.length; ...) {

抱歉,如果这真的很基本/很明显,我真的被卡住了。谢谢你的帮助。

4

1 回答 1

0

我假设您想比较数组中的各个数字,您可以使用基本循环并检查:

for (var i = 0; i < list1.length; i++) {
    if (list1[i] > list2[i]) { //its greater! }
    else if (list1[i] < list2[i]) { //its less! }
    else { //they must be equal }
}

此外,公平警告,document.write每次都会重写您的页面!

于 2013-10-03T02:45:10.480 回答