Reputation: 887
The call to n.sort(sortNo)
doesn't specify any parameters for the function sortNo
(which defines parameters of a
and b
). Can anyone explain why?
<script type="text/javascript">
function sortNo(a,b)
{
return a - b;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNo));
</script>
Is return a - b;
the formulae used?
I know that sortNo
is provided with two items. Does a numerical operation return the following?
a
is before b
b
is before a
a
and b
are equalUpvotes: 2
Views: 3221
Reputation: 6277
Both a and b are strings. So a-b makes no sense.
Use
function sortNumber(a,b)
{
if (a < b)
return 1;
else if(a>b)
return -1;
return 0;
}
Upvotes: 1
Reputation: 1038910
This is because the Array.sort
method expects a function pointer as argument. It will then loop through the array and invoke this function. You could also have used an anonymous function:
n.sort(function(a, b) {
return a- b;
});
Upvotes: 4