我有点头脑,但我想知道是否有人可以帮助我这个:
取自: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.");
Run Code Online (Sandbox Code Playgroud)
我认为它应该是:
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.");
Run Code Online (Sandbox Code Playgroud)
但这给了我未定义的错误.
你不是在数组上调用它.
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.");
Run Code Online (Sandbox Code Playgroud)
几乎[]可以工作(可以是任何数组).但是,您仍然没有转换arguments为数组,也没有slice使用call或调用apply.这是演习的重点.
此外,它没有任何意义,因为您没有使用数组的内容.
因此,解决方案是:
function highest(){
return Array.prototype.slice.call(arguments, 1).sort(function(a,b){
return b - a;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1100 次 |
| 最近记录: |