You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化JavaScript井字棋赢线检测:更高效的嵌套数组匹配代码

井字棋赢线检测代码优化方案

原代码存在依赖全局变量、判断逻辑繁琐、查找效率偏低的问题,以下是几种更简洁高效的优化写法:

基础优化版(核心逻辑简化)

const wins = [[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]];

const moves = [0,5,2,4,3]; // 示例走法列表

function checkWin(moves) {
  const moveSet = new Set(moves);
  // 遍历赢线,检查是否所有位置都被占据
  for (const line of wins) {
    if (line.every(square => moveSet.has(square))) {
      console.log("win");
      return true;
    }
  }
  return false;
}

// 执行检测
checkWin(moves);

优化点说明:

  • 移除全局变量:将检测逻辑封装为独立函数,所有变量作用域限制在函数内部,避免全局污染,提升代码复用性。
  • 提升查找效率:把moves转为Set,利用Set.has()的O(1)查找性能,替代原代码中Array.some()的O(n)遍历,大幅提升判断速度。
  • 简化判断逻辑:用Array.every()直接判断赢线的所有位置是否都在走法集合中,替代原代码收集布尔数组后用JSON.stringify对比的冗余操作,逻辑更直观。
  • 提前终止循环:找到有效赢线后立即返回结果,无需遍历剩余赢线,减少不必要的计算。

扩展版(返回赢线信息)

如果需要获取具体的获胜线路,可以修改函数返回对应赢线:

function checkWin(moves) {
  const moveSet = new Set(moves);
  for (const line of wins) {
    if (line.every(square => moveSet.has(square))) {
      console.log(`获胜线路:${line.join(', ')}`);
      return line;
    }
  }
  return null; // 未获胜返回null
}

const result = checkWin(moves);

内容的提问来源于stack exchange,提问作者Dave022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:45:31