Zha*_* Yi 19 javascript lodash
我有下面的代码,我试图用来lodash
从数组对象中找到最大值;
var a = [ { type: 'exam', score: 47.67196715489599 },
{ type: 'quiz', score: 41.55743490493954 },
{ type: 'homework', score: 70.4612811769744 },
{ type: 'homework', score: 48.60803337116214 } ];
var _ = require("lodash")
var b = _.max(a, function(o){return o.score;})
console.log(b);
Run Code Online (Sandbox Code Playgroud)
输出47.67196715489599
不是最大值.我的代码出了什么问题?
Ori*_*ori 37
Lodash _.max()
不接受iteratee(回调)._.maxBy()
改为使用:
var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
console.log(_.maxBy(a, function(o) {
return o.score;
}));
// or using `_.property` iteratee shorthand
console.log(_.maxBy(a, 'score'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
甚至更短:
var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
const b = _.maxBy(a, 'score');
console.log(b);
Run Code Online (Sandbox Code Playgroud)
这使用_.property
iteratee的简写。