我想用javascript做简单但需要最快的方法:
我有这个数组:
players: [{
isInjured : false,
name: ...
stamina : 50
},{
isInjured : true,
name: ...,
stamina : 20
}
...
]
我想以最快最好的方式做两件事:
1)如果我在数组中的“ injured”属性为true,对任何人。
2)我想提取3个最低耐力球员,并提取其中一个的关键。
如果可能的话,我想避免为此做2次forEach,那么最好的方法是什么?
最佳答案
var players = [{
isInjured: false,
stamina: 50
}, {
isInjured: false,
stamina: 10
}, {
isInjured: false,
stamina: 15
}, {
isInjured: false,
stamina: 16
}, {
isInjured: true,
stamina: 20
}];
// Your second request you can do with lodash or underscore easily
var threePlayersWithMinStamina = _.take(_.sortBy(players, function(player) {
return player.stamina;
}), 3);
console.log(threePlayersWithMinStamina) // you have the three players with the min stamina
//Your first request
// the var isOneInjured will be true if the condition will be true and stop the loop
var isOneInjured = players.some(function(player) {
return player.isInjured;
});
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>