开发者

John Resig Advanced Javascript Question

Im in a little over my head, but I was wondering if anyone can help me with this one:

taken from: 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.");

I thought it should be:

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.");

But this is giving me errors of undefined.


You're not calling it on an array.

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.");

would almost work ([] can be any array). However, you still didn't convert arguments to an array, nor did you call slice with call or apply. That's the main point of the exercise.

Also, it doesn't make any sense, since you're not using the contents of the array.

Thus, the solution is:

function highest(){ 
  return Array.prototype.slice.call(arguments, 1).sort(function(a,b){ 
    return b - a; 
  }); 
}


The way you're defining the function would work by adding a method to all arrays:

[1,2,3].highest()

The original function is meant to be called as a regular function:

highest(1,2,3)

Anyways, the problem with the original code has nothing to do with this. The trouble is that arguments is not really an array, so you need to convert it using Array.prototype.slice.call(arguments) before you can call slice on it.

The correct answer is:

function highest(){
  return Array.prototype.slice.call(arguments).slice(1).sort(function(a,b){
    return b - a;
  });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜