John Resig高级Javascript问题

时间:2010-11-29 08:18:09

标签: javascript

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

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

但是这给了我未定义的错误。

2 个答案:

答案 0 :(得分:6)

你没有在阵列上调用它。

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转换为数组,也未使用callapply调用slice。这是演习的重点。

此外,它没有任何意义,因为你没有使用数组的内容。

因此,解决方案是:

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

答案 1 :(得分:2)

您定义函数的方式可以通过向所有数组添加方法来实现:

[1,2,3].highest()

原始函数应该被称为常规函数:

highest(1,2,3)

无论如何,原始代码的问题与此无关。问题是arguments实际上不是一个数组,因此您需要先使用Array.prototype.slice.call(arguments)进行转换,然后才能在其上调用slice

正确答案是:

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