将猜测游戏变为降序

时间:2016-02-26 11:39:48

标签: javascript

此脚本有效,产生随机数。例如;点击按钮时;你得到一个如下所示的列表:

 579 too high
 520 too high
 392 too high
 273 too high
 90 too high
 58 too high
 24 too high
 6 too low
 20 too high
 19 too high
 13 too high
 9 too low
 12 Got it !!!

它会显示高低混合的随机数。 我如何将这个程序变成一个排序列表,而不是显示:

579 too high
520 too high
392 too high
173 too high
120 too high
90 too high
87 too high
50 too high
39 too high
12 too high
9 too low
4 Got it !!!

如何让这个程序按降序排列? JsFiddle Guessing Game

代码就在这里:

猜测:          
获得号码:

<button id="click" onclick="InsertGuess(1000,0,'',0)">Generate</button>
<div id="guess"></div>





var InsertGuess = function(max,min,finalStr,count) {
var str = 'Guessed :';
var guessnum = Math.floor(Math.random() *(max-min+1)+min);

 if(document.getElementById('index').value > guessnum){
 finalStr = finalStr.concat(guessnum , ' too low <br>');
 count=count+1;
return InsertGuess(max,guessnum,finalStr,count);
 }else if(document.getElementById('index').value < guessnum) {
 finalStr = finalStr.concat(guessnum, ' too high <br>');
 count=count+1;
 return InsertGuess(guessnum,min,finalStr,count);
 }else{
 count=count+1;
 finalStr = finalStr.concat(guessnum , ' Got it !!!<br>');
 finalStr = finalStr.concat('It took me '+ count +' tries ');
 document.getElementById('guess').innerHTML= finalStr;
 return ;
 }
 }

我搜索过如何降序和升序;但是,它不会起作用。

1 个答案:

答案 0 :(得分:0)

不是连接字符串,而是将变量(finalStr)设为数组,让我们将其称为finalArr。然后,不是使用concat,而是将每一行作为数组元素推送;

 finalArr.push(guessnum , ' too low <br>');

然后在完成所有推送后,将数组从低到高排序

finalArr.sort();

您可能必须查看该排序函数,因为它可能不适用于数字(例如,它可能会将11视为低于2)。但我至少让你开始了。