Javascript arguments.sort()抛出错误排序不是一个函数 [英] Javascript arguments.sort() throw error sort is not a function
问题描述
只是想知道为什么我使用以下简单的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);
错误消息:TypeError:arguments.sort不是函数。
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
推荐答案
因为参数
没有 sort
方法。请注意参数
不是 Array
对象,它是一个类似于数组 参数
对象。
Because arguments
has no sort
method. Be aware that arguments
is not an Array
object, it's an array-like Arguments
object.
但是,您可以使用 Array.prototype.slice
将参数
转换为数组;然后你就可以使用 Array.prototype.sort
:
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]
这篇关于Javascript arguments.sort()抛出错误排序不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!