只是想知道为什么以下简单的JavaScript函数会出错
function highest(){
return arguments.sort(function(a,b){
return b - a;
});
}
highest(1, 1, 2, 3);
错误消息:TypeError:arguments.sort不是函数。
我很困惑,因为它是一个数组(我认为)。请帮助并解释原因。非常感谢
因为arguments
没有sort
办法。请注意,这arguments
不是一个Array
对象,而是一个类似数组的Arguments
对象。
但是,可以使用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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句