Just wondering why i got an error with the following simple JavaScript function
function highest(){
return arguments.sort(function(a,b){
return b - a;
});
}
highest(1, 1, 2, 3);
Error messsage : TypeError: arguments.sort is not a function.
I am confused as arguments it is an array (i thought). Please help and explain why. Many thanks
Because arguments
has no sort
method. Be aware that arguments
is not an Array
object, it's an array-like Arguments
object.
However, you can use Array.prototype.slice
to convert arguments
to an array; and then you will be able to use Array.prototype.sort
:
function highest(){
return [].slice.call(arguments).sort(function(a,b){
return b - a;
});
}
highest(1, 1, 2, 3); // [3, 2, 1, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With