我想做简单但需要以最快的方式在javascript中执行此操作:
我有这个数组:
players: [{
isInjured : false,
name: ...
stamina : 50
},{
isInjured : true,
name: ...,
stamina : 20
}
...
]
我想以最好,最快的方式做两件事:
1)如果我在数组中的“inInjured”属性中为true,则为任何人。
2)我想提取3个最低耐力的球员,并提取其中一个的关键。
如果可能的话,我想避免为此做2 forEach,那么最好的方法是什么?
答案 0 :(得分:2)
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>
&#13;
答案 1 :(得分:1)
使用数组本机some函数,如下文
var isSomeoneInjurd = players.some(function(pl){
return pl.isInjured;
});
如果任何玩家的财产isSomeoneInjurd
为真,则isInjured
的值为true。一旦它获得该属性的真实,它就会打破循环。