简体   繁体   English

我可以指定一个变量来检查循环中的多个数组吗?

[英]Can I assign a variable to check multiple arrays inside a loop?

I am trying to check through multiple arrays inside of a loop, all with the same index. 我试图检查循环内的多个数组,所有数组都具有相同的索引。 Instead of manually coding through every list I wanted to soft code it so every time the function loops it can check through all of my arrays. 我没有手动编码每个列表,而是想对它进行软编码,所以每次函数循环时它都可以检查我的所有数组。 All of my arrays are named: score1-score8, but whenever this code runs it doesn't actually check any of the lists. 我的所有数组都命名为:score1-score8,但每当此代码运行时,它实际上不会检查任何列表。

function checkHorizontal()
{

    var rowcount=0;
    var checkLists;
    var player1=0;
    var player2=0;

    checkLists="score"+rowcount;

    for (var i = 0; rowcount <= 8; i++) 
    {
        rowcount+=1;
        if(checkLists[rowcount]==1) 
        {
            player1+=1;
            player2=0;    
        }
        else if (checkLists[rowcount]==2)
        {
            player2+=1;
            player1=0;
        }

    }

}

Instead of giving each score a variable name that has an index, you can save the scores in an array and use another for loop. 您可以将分数保存在数组中并使用另一个for循环,而不是为每个分数指定具有索引的变量名称。

Here's an example, assuming: 这是一个例子,假设:

  • We have two players 我们有两名球员
  • A game consists of an unknown number of sets 游戏由未知数量的集合组成
  • A set consists of an unknown number of legs 一组由未知数量的腿组成

 const player1 = 1; const player2 = 2; const set1 = [ 1, 2, 1 ]; const set2 = [ 1, 2, 2 ]; const set3 = [ 2, 2, 1 ]; let player1Score = 0; let player2Score = 1; // Create a new array containing all sets: const game = [ set1, set2, set3 ]; // Loop over every set in the game for (let s = 0; s < game.length; s += 1) { const set = game[s]; // Loop over the legs in every set for (let g = 0; g < set.length; g += 1) { const winner = set[g]; if (winner === player1) player1Score += 1; if (winner === player2) player2Score += 1; } } console.log(`The final match score is player1 ${player1Score} vs player2 ${player2Score}`); 

For your specific case, you could define game as [ score1, score2, score3, score4, score5, score6, score7, score8 ] 对于您的具体情况,您可以将game定义为[ score1, score2, score3, score4, score5, score6, score7, score8 ]

If the number of players can also differ, you could add them to an array as well! 如果玩家数量也不同,您也可以将它们添加到阵列中! You'd get a third loop, checking to which player you need to assign a point for every leg you process. 你会得到第三个循环,检查你需要为你处理的每条腿分配一个点的玩家。

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

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