0

下面给出的代码给出了一个错误arguments.sort不是函数。是因为参数对象不能直接改变吗?或者是别的什么。

任何帮助,将不胜感激。

function highest()
{ 
    return arguments.sort(function(a,b){ 
         return b - a; 
    }); 
} 
assert(highest(1, 1, 2, 3)[0] == 3, "Get the highest value."); 
assert(highest(3, 1, 2, 3, 4, 5)[1] == 4, "Verify the results.");

assert功能如下(以防万一)

function assert(pass, msg){
   var type = pass ? "PASS" : "FAIL";
   jQuery("#results").append("<li class='" + type + "'><b>" + type + "</b> " + msg + "</li>");
}
4

3 回答 3

4

试试这个:

return [].sort.call(arguments, function(a, b) {
   return b - a;
})

编辑:正如@Esailija 指出的那样,这不会返回一个真正的数组,它只是返回arguments一个类似数组的对象。按索引迭代和访问属性很好,但仅此而已。

于 2013-03-07T09:40:55.730 回答
2

这是因为arguments不是数组,也没有sort方法。

您可以使用此技巧将其转换为数组:

function highest()
{ 
    return [].slice.call(arguments).sort(function(a,b){ 
         return b - a; 
    }); 
} 
于 2013-03-07T09:40:25.783 回答
0

您的最高功能没有在内部传递任何参数

function highest(arguments)
{ 
    return arguments.sort(function(a,b){ 
         return b - a; 
    }); 
} 

并且应该使用数组

highest([1, 1, 2, 3])[0]
于 2013-03-07T09:47:09.533 回答