Javascript arguments.sort() 抛出错误排序不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28311196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript arguments.sort() throw error sort is not a function
提问by Bill
Just wondering why i got an error with the following simple JavaScript function
只是想知道为什么我在使用以下简单的 JavaScript 函数时出现错误
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.
错误消息:TypeError:arguments.sort 不是函数。
I am confused as arguments it is an array (i thought). Please help and explain why. Many thanks
我很困惑,因为它是一个数组(我认为)。请帮忙解释原因。非常感谢
回答by Oriol
Because argumentshas no sortmethod. Be aware that argumentsis not an Arrayobject, it's an array-like Argumentsobject.
因为arguments没有sort办法。请注意,这arguments不是一个Array对象,它是一个类似数组的Arguments对象。
However, you can use Array.prototype.sliceto convert argumentsto an array; and then you will be able to use Array.prototype.sort:
但是,您可以使用Array.prototype.slice转换arguments为数组;然后你将能够使用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]
回答by Ashok R
回答by iamnagaky
Another way to do this is by declaring the arguments as an array.
另一种方法是将参数声明为数组。
var myArguments = [1, 1, 2, 3];
var sortedArguments = [];
Thus the highest() can be defined as;
因此,highest() 可以定义为;
function highest(myArguments)
{
return myArguments.sort(function(a,b)
{
return b - a;
});
}
sortedArguments = highest(myArguments);


