我是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>";
发布于 2015-05-17 18:54:02
好了,我编辑了我的答案,我希望这段代码能帮助你:
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>';
}
发布于 2015-05-17 19:19:20
你的问题相当模糊,但你可以试试这个:
var timeStart = 0;
var output = [];
function timeGenerator(timeStart) {
var time = Math.floor(Math.random() * 90 + 1);
if (time > timeStart) {
timeStart = time;
}
output.push(timeStart);
output.sort();
;
document.getElementById("Scorers").innerHTML = "</p>"+ output.toString() +"</p>";
}
它将排序后的数字保存在一个数组中,该数组总是重新打印到元素中。
https://stackoverflow.com/questions/30286044
复制相似问题