如何实现满足匹配条件时判定获胜并终止循环(行/列5个,对角线4个)
问题描述
现有一段JavaScript代码,定义了包含行、列、对角线位置的winningTemplate对象,当前代码遍历该对象的数组元素,检查updatedBirdClonePlayerOne对应位置的元素是否包含'match'。目前已能检测到匹配元素,但需要修改逻辑:当任意行/列的5个元素均匹配,或任意对角线的4个元素均匹配时,判定获胜并终止所有循环,寻求实现方案。
原代码如下:
const winningTemplate = { firstRow: [0, 1, 2, 3, 4], secondRow: [5, 6, 7, 8, 9], thirdRow: [10, 11, 13, 14], fourthRow: [15, 16, 17, 18, 19], lastRow: [20, 21, 22, 23, 24], firstDiagonal: [0, 6, 18, 24], firstColumn: [0, 5, 10, 15, 20], secondColumn: [1, 6, 11, 16, 21], thirdColumn: [2, 7, 17, 22], fourthColumn: [3, 8, 13, 18, 23], lastColumn: [4, 9, 14, 19, 24], lastDiagonal: [4, 8, 16, 20], } export default winningTemplate; let checkTemplate = Object.values(winningTemplate) let isWinner = 0 for (let checkWinner of checkTemplate) { for (let checkMatchedBird of checkWinner) { const newWinnerMatchedArray = updatedBirdClonePlayerOne[checkMatchedBird] console.log('newWinnerMatchedArray', newWinnerMatchedArray) if (newWinnerMatchedArray.includes('match')) { break } // setWinner('wins') } // break; }
实现方案
核心逻辑是对每个获胜模板(行/列/对角线),验证其所有位置的元素都包含'match',一旦找到符合条件的模板,立即终止所有循环并判定获胜。
- 遍历每个模板时,统计当前模板中满足
includes('match')的元素数量 - 直接对比统计数与模板自身的长度(行/列数组长度为5,对角线为4,无需单独判断类型)
- 找到符合条件的模板后,立即执行获胜逻辑并终止所有遍历
修改后的代码
方案1:标记变量+多层循环(直观易读)
import winningTemplate from './winningTemplate'; // 按实际路径引入 let checkTemplate = Object.values(winningTemplate); let isWinner = false; // 给外层循环加标签,方便跳出所有循环 outerLoop: for (let template of checkTemplate) { let matchedCount = 0; for (let index of template) { const element = updatedBirdClonePlayerOne[index]; if (element.includes('match')) { matchedCount++; } else { // 只要有一个位置不匹配,直接跳过当前模板 break; } } // 检查当前模板是否全部匹配 if (matchedCount === template.length) { isWinner = true; setWinner('wins'); // 执行你的获胜逻辑 break outerLoop; // 终止所有循环 } }
方案2:使用数组方法简化代码(更简洁高效)
import winningTemplate from './winningTemplate'; // some()会在找到第一个符合条件的模板后立即停止遍历 const isWinner = Object.values(winningTemplate).some(template => { // every()验证模板中所有位置都满足匹配条件 return template.every(index => updatedBirdClonePlayerOne[index].includes('match')); }); if (isWinner) { setWinner('wins'); // 执行你的获胜逻辑 }
内容的提问来源于stack exchange,提问作者Ihsanullah Mahboobi
相关产品推荐
相关产品推荐

