我有点不知所措,但我想知道是否有人可以帮助我解决这个问题:
取自:http://ejohn.org/apps/learn/#43
function highest(){
return arguments.slice(1).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.");
我认为应该是:
Array.prototype.highest = function(){
return arguments.slice(1).sort(function(a,b){
return b - a;
});
}
assert(highest(1, 1, 2, 3)[0] == 1, "Get the highest value.");
assert(highest(3, 1, 2, 3, 4, 5)[1] == 1, "Verify the results.");
但这给我带来了未定义的错误。
最佳答案
您不是在数组上调用它。
assert([].highest(1, 1, 2, 3)[0] == 1, "Get the highest value.");
assert([].highest(3, 1, 2, 3, 4, 5)[1] == 1, "Verify the results.");
几乎可以工作([]
可以是任何数组)。但是,您仍然没有将 arguments
转换为数组,也没有使用 call
调用 slice
或 apply
.这是练习的重点。
此外,它没有任何意义,因为您没有使用数组的内容。
因此,解决方案是:
function highest(){
return Array.prototype.slice.call(arguments, 1).sort(function(a,b){
return b - a;
});
}
关于javascript - John Resig 高级 Javascript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4301920/