Javascript Sorting Numbers

江枫思渺然 提交于 2019-12-10 21:04:48

问题


I am trying to sort the number in descending order using javascript. It works well for strings but when I use numbers it gives me wrong results.

Following is the code:

<html>
<head>
<script language ="Javascript">
function sort(form)
{
var a1=form.first.value
var b1 = form.second.value
var c1 =form.third.value
var a2= parseFloat(a1)
var b2=parseFloat(b1)
var c2= parseFloat(c1)
var rank_the_numbers = [a2,b2,c2]
rank_the_numbers.sort(function(a, b){return a-b})


document.writeln("The largest number is: "+rank_the_numbers[0])
document.writeln("<br> The second largest number is: " +rank_the_numbers[1])
 document.writeln("<br> The smallest number is: " +rank_the_numbers[2])
 document.writeln(rank_the_numbers)
}
</script>
</head>
<form onSubmit="return sort(this)">
Enter any three numbers: <br>
<input type="text" name="first" size=5><br>
<input type="text" name="second"size=5><br>
<input type="text" name="third" size=5><br>
<input type="submit" value= "Rank the numbers!" onClick = "sort(this.form)">
</form>
</body>
</html>

What changes should i make so that the code runs correctly for the numbers too. I went through a few articles on stackoverflow and used (function(a, b){return a-b}), but it too did not work.


回答1:


For decending order

sort should be

rank_the_numbers.sort(function (a, b) {
    return b - a;
});

JSFIDDLE



来源:https://stackoverflow.com/questions/33676888/javascript-sorting-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!