简体   繁体   English

比较来自不同对象的数组属性值

[英]Compare array property values from different objects

I have an object called "Player" with properties such as "score", "turns", "name", etc. Based on how many players the user chooses to have, I create an array of players. 我有一个名为“ Player”的对象,具有诸如“得分”,“转弯”,“名称”等属性。根据用户选择拥有的玩家数量,我创建了一个玩家数组。

As the game is played, I update each player's score. 玩游戏时,我会更新每个玩家的分数。 What I need to do is compare the "score" from the current player against all the other players. 我需要做的是将当前玩家的“得分”与所有其他玩家的得分进行比较。 If it is higher, said player wins. 如果更高,则表示玩家获胜。 Currently the only way I've been able to do this is to create a temporary array with the score values of all players and reorder the array from highest to lowest. 目前,我能够做到这一点的唯一方法是使用所有玩家的得分值创建一个临时数组,并将数组从高到低重新排序。 I am then checking to see if the current player's score is the same as the score in the 0 index of my temp array. 然后,我要检查当前玩家的分数是否与我的临时数组0索引中的分数相同。 This can cause potential problems though, as two players COULD have the same score, at which point I have no way of correlating the score in the temp array with the player to whom it belongs to. 但是,这可能会导致潜在的问题,因为两个玩家可能具有相同的分数,这时我无法将临时数组中的分数与其所属的玩家相关联。

Is what I'm currently doing the best possible choice? 我目前正在做的最好的选择是什么? There has to be a way to optimize this. 必须有一种优化方法。 Thanks for any help! 谢谢你的帮助!

You could just look through the array for the highest score and then see if that's your player or not. 您可以只查看最高得分的数组,然后查看是否是您的玩家。

var playerInfo = [
    {name: "Bob", score: 70},
    {name: "Jill", score: 98},
    {name: "Ted", score: 96}
];

function findHighestScore() {
    // assumes there is always at least one entry in the playerInfo array
    var highestIndex = 0;
    var highestScore = playerInfo[0].score;
    for (var i = 1; i < playerInfo.length; i++) {
        if (playerInfo[i].score > highestScore) {
            highestIndex = i;
            highestScore = playerInfo[i].score;
         }
     }
     return(highestIndex);
}

Why can't you iterate over the array of players and simply check the score of each versus the current player? 您为什么不能遍历所有玩家并仅检查每个玩家与当前玩家的得分?

Instead of keeping an Array of scores could you keep an array of players sorted by their score? 除了保留一系列分数之外,您还可以保留一系列按其分数排序的玩家吗?

Does this help? 这有帮助吗?

http://www.javascriptkit.com/javatutors/arraysort2.shtml http://www.javascriptkit.com/javatutors/arraysort2.shtml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM