gpt4 book ai didi

javascript - 比较两列中的随机数字集

转载 作者:行者123 更新时间:2023-11-28 08:50:49 24 4
gpt4 key购买 nike

这里的目标是使用 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; ...) {

抱歉,如果这真的很基本/显而易见,我只是真的陷入困境。感谢您的帮助。

最佳答案

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

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 每次都会重写您的页面!

关于javascript - 比较两列中的随机数字集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com