gpt4 book ai didi

javascript - 在不超过特定值的对象数组中找到最大值 - Javascript

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

我有一个对象数组,想找到得分最高且不超过特定分数(例如 20 分)的玩家。我该怎么做?

    let playerScores = [ 
{ player: 'Dealer',
score: 19,
cards: 'A of ♥, 5 of ♦' },
{ player: 'Player1',
score: 18,
cards: '10 of ♦, 8 of ♦' },
{ player: 'Player2',
score: 23,
cards: '6 of ♦, 6 of ♥, J of ♠' }
]

console.log(playerScores)
// iterates through playerScores
for (let i in playerScores) {
if (playerScores[i].score > 20) {
console.log(playerScores[i].player + ' BUSTED!')
// removes the object with a score over 21 from the array
playerScores.splice(i,1)
}
return playerScores
}

最佳答案

可以先过滤数据,按分数排序,然后取第一个:

let filteredData = playerScores.filter(p=>p.score<=20).sort((a,b) => b.score-a.score);
let result = filteredData.length ? filteredData[0] : undefined;`

关于javascript - 在不超过特定值的对象数组中找到最大值 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48037904/

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