Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript arguments.sort() throw error sort is not a function

Tags:

javascript

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

like image 217
Bill Avatar asked Feb 04 '15 00:02

Bill


1 Answers

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]
like image 187
Oriol Avatar answered Sep 20 '22 11:09

Oriol