首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将数字从小到大排序的随机数生成器

将数字从小到大排序的随机数生成器
EN

Stack Overflow用户
提问于 2015-05-17 18:46:58
回答 2查看 98关注 0票数 3

我是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>";
EN

回答 2

Stack Overflow用户

发布于 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>';
}

Demo

票数 1
EN

Stack Overflow用户

发布于 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>";
}  

它将排序后的数字保存在一个数组中,该数组总是重新打印到元素中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30286044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档