javascript - John Resig 高级 Javascript 问题

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

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

最佳答案

您不是在数组上调用它。

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 调用 sliceapply .这是练习的重点。

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

因此,解决方案是:

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/

相关文章:

javascript - 如何使用Coffeescript和shellJS编写可执行的shell脚本?

javascript - 如何在 ASP.NET 中将 JSON 数据格式化为 JavaScript 序列化器

javascript - 组合 'var' 语句

javascript - Slick Slider Carousel 同步行重叠(w/JSFiddle)。我难住了

javascript - Angular JS 1 - 添加框架时出错

javascript - 在 wordpress 3.9.1 媒体上传上添加自定义菜单项

javascript - node.js 需要一个 json 文件

javascript - 缺少一些试图将 Bootstrap 作为本地 git 子模块包含到 meteor 中的东西

javascript - 由于 ie8 兼容模式的特殊 css,我如何使用 JavaScript 为媒体打印编写 css?

javascript - ng-repeat 过滤器不适用于引号