gpt4 book ai didi

javascript - 随机数生成器,将数字从小到大排序

转载 作者:行者123 更新时间:2023-11-29 15:35:01 30 4
gpt4 key购买 nike

我是 JavaScript 的新手,我正在尝试编写一个函数来生成 0 到 90 之间的数字,并将该数字返回到 HTML 文件。我正在尝试从小到大排序,这是我的代码,但它没有排序。

var timeStart = 0;

function timeGenerator(timeStart) {
var time = Math.floor(Math.random() * 90 + 1);
if (time > timeStart) {
timeStart = time;
}
return timeStart;
}
document.getElementById("Scorers").innerHTML += '<p>'+Scorers[Math.floor(Math.random() * 10)]+' '+timeGenerator(timeStart)+"'</p>";

最佳答案

好的,所以我编辑我的答案,我希望这段代码能帮到你:

var Players = ["Player1", "Player2", "Player3"];
var Scorers = [];

function newScore(player, time){
tuple = [time, player];
Scorers.push(tuple);
}

newScore(Players[0], parseInt(Math.floor(Math.random()*90+1)), 10);
newScore(Players[1], parseInt(Math.floor(Math.random()*90+1)), 10);
newScore(Players[2], parseInt(Math.floor(Math.random()*90+1)), 10);

// Order
Scorers.sort(function(current, next){ return current[0] - next[0];});

for (i=0; i < Scorers.length; i++){
document.getElementById("Scorers").innerHTML += '<p>'+Scorers[i][1]+ ' - ' + Scorers[i][0] + '</p>';
}

Demo

关于javascript - 随机数生成器,将数字从小到大排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286044/

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