Can someone walk me through it? I don't understand what parameters are passed and things like that.
<html>
<body>
<script type="text/javascript">
function sortNumber(a, b)
{
return b - a;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
</script>
</body>
</html>
sort
will compare a
to b
, and change the array to be in descending order.
The -
operator will coerce them to Number
.
If you want to see the members being passed as a
and b
, output them with something like console.log
(if you have a console object).
The function sortNumber will return something less than 0, 0 or something larger than 0. this will tell the sort which of the compared strings are numerically larger
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
This link will help you understand:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.