gpt4 book ai didi

javascript - 找出对象是否具有某种属性和真实性的最快方法?

转载 作者:行者123 更新时间:2023-11-28 18:57:18 24 4
gpt4 key购买 nike

我想做简单的事情,但需要在 javascript 中以最快的方式做到这一点:

我有这个数组:

   players: [{
isInjured : false,
name: ...
stamina : 50
},{
isInjured : true,
name: ...,
stamina : 20
}
...
]

我有两件事想要以最好、最快的方式做:

1)如果我在数组中的“inInjured”属性中为 true,则对任何人都有效。

2)我想提取3个体力最低的玩家,并提取其中之一的 key 。

如果可能的话,我想避免为此执行 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>

关于javascript - 找出对象是否具有某种属性和真实性的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33364206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com