亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

找到相同的數組時如何停止運行循環?

找到相同的數組時如何停止運行循環?

LEATH 2022-07-08 15:59:39
我正在做一個井字游戲。winningPlays棋盤上的每個方塊都有一個從 0 到 8 的索引。為了檢查獲勝者,我有一個包含所有潛在獲勝組合的二維數組。我有兩個數組,分別包含 Xs 或 Os -xPlays和的播放oPlays。排序后xPlays,我想比較它以winningPlays查看是否有任何數組匹配。如果他們這樣做,我想console.log('X wins')。我似乎找不到在正確的時間執行 console.log 以確定獲勝者的方法。這是一段問題代碼:const winningPlays = [        [0,1,2], //across top        [3,4,5], //across middle        [6,7,8], //across bottom        [0,3,6], //left down        [1,4,7], //middle down        [2,5,8], //right down        [0,4,8], //top left to bottom right        [2,4,6] // top right to bottom left    ]; //length == 8    function checkForWinner() {        for(let i = 0; i < winningPlays.length; i++){            for(let j = 0; j < winningPlays[i].length; j++){                if (xPlays.length < 3) {                    return;                } else if (winningPlays[i][j] !== xPlays[j]) {                    console.log(winningPlays[i][j])                    console.log(xPlays[j])                    return;                }                console.log('win')  // executes every time that xPlays.length >= 3            }        }     };這是我的 codepen 草稿的鏈接:https ://codepen.io/CDLWebDev/pen/gOawjvE
查看完整描述

3 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

你有幾個問題。


首先,一旦發現不匹配,就從函數返回,但后面的元素winningPlays可能匹配。


其次,您期望xPlays完全匹配其中一個winningPlays元素。但是 X 可以有額外的玩法。例如,如果xPlays = [2, 3, 4, 5], that should match[3, 4, 5] . What you really want to test is if all the elements of one of thewinningPlays elements are included inxPlays`,它們不必具有相同的索引。


function checkForWinner() {

  if (xPlays.length < 3) {

    return;

  }

  for (let i = 0; i < winningPlays.length; i++) {

    let win = true;

    for (let j = 0; j < winningPlays[i].length; j++) {

      if (!xPlays.includes(winningPlays[i][j])) {

        win = false;

        break;

      }

    }

    if (win) {

      console.log('win');

      break;

    }

  }

}


查看完整回答
反對 回復 2022-07-08
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

遍歷每個子數組

檢查該子數組的所有項目是否都存在于玩家數組中

function checkWinner() {

    return winningPlays.some(list => {

        return list.every(item => {

            return xPlays.includes(item);

        });

    });

}


查看完整回答
反對 回復 2022-07-08
?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

我會通過執行以下操作使其更簡單


const winningPlays = [

    "0,1,2", //across top

    "3,4,5", //across middle

    "6,7,8", //across bottom

    "0,3,6", //left down

    "1,4,7", //middle down

    "2,5,8", //right down

    "0,4,8", //top left to bottom right

    "2,4,6" // top right to bottom left

]; //length == 8


function checkForWinner(xPlays) {

    var convertXPlays = xPlays.toString(); //if there are spaces in your array, make sure to remove it

    if (winningPlays.indexOf(convertXPlays) > -1)

    {

       console.log('win!');

    }

};


查看完整回答
反對 回復 2022-07-08
  • 3 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號