John Resig高级Javascript问题 [英] John Resig Advanced Javascript Question

查看:67
本文介绍了John Resig高级Javascript问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点过头了,但我想知道是否有人可以帮我这个:

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

取自: http://ejohn.org/apps/learn/#43

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

我认为应该是:

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

几乎可以工作( [] 可以任何数组)。但是,您仍然没有将 arguments 转换为数组,也没有使用 slice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call\"rel =noreferrer> 致电 apply 。这是练习的重点。

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.

因此,解决方案是:

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

这篇关于John Resig高级Javascript问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆