2013-03-07 103 views
0

下面给出的代码给出了一个错误arguments.sort不是函数。是因为论点对象不能直接更改?或者是别的什么。Javascript“not a function”

任何帮助,将不胜感激。

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

试试这个:

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

编辑:作为@Esailija指出的,这不返回现实数组,它只是返回arguments对象,它是一个类似数组的对象。按索引迭代和访问属性很好,但这就是它。

+0

谢谢,这有很大的帮助。 – clu3Less 2013-03-07 09:45:47

+0

但是这不返回一个数组:x – Esailija 2013-03-07 09:47:12

+0

@Esailija:没错,没有注意到它返回一个'arguments'对象。对于这种情况应该没问题,但是OP可能需要一个实际的数组。 – elclanrs 2013-03-07 09:50:29

2

这是因为arguments不是数组和不具有sort方法。

您可以使用这一招将其转换为一个数组:

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

感谢那些帮助了很多。 – clu3Less 2013-03-07 09:46:03

0

您最高的功能未经过任何论证内

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

,并应与一个阵列工作

highest([1, 1, 2, 3])[0] 
相关问题