如何用JavaScript变量指代多值并解决游戏玩家切换代码报错问题?
问题解决:JS双人游戏中通过玩家变量关联元素的正确方式
你的核心错误是直接用模板字符串语法拼接变量名(IMAGES_${player[1]}),这种写法在JS里无法解析为对应的全局变量IMAGES_2,导致报错。下面给你两种实用的解决方案:
方案1:用对象数组统一管理玩家元素(推荐,易维护)
把每个玩家的所有关联元素封装成对象,存入数组,后续通过玩家索引直接调用,彻底避免重复代码:
"use strict"; // 按玩家分组存储所有相关元素 const players = [ { element: document.querySelector(".player-1"), total: document.querySelector(".total-1"), current: document.querySelector(".borders-1"), images: document.querySelector(".images-1") }, { element: document.querySelector(".player-2"), total: document.querySelector(".total-2"), current: document.querySelector(".borders-2"), images: document.querySelector(".images-2") } ]; // 标记当前轮到的玩家(0=玩家1,1=玩家2) let currentPlayerIndex = 0; // 给当前玩家的images元素添加hidden类 players[currentPlayerIndex].images.classList.add("hidden"); // 条件判断(注意:contains里不要加.,直接写类名) if (players[currentPlayerIndex].images.classList.contains("active")) { // 你的业务逻辑代码 }
切换玩家时只需要修改currentPlayerIndex(比如currentPlayerIndex = 1 - currentPlayerIndex就能在两位玩家间切换),所有操作逻辑完全复用,不会出现冗余代码。
方案2:通过window对象访问全局变量(快速修改,不推荐长期使用)
如果不想重构现有变量结构,可以利用全局变量挂载在window对象上的特性,用字符串拼接获取变量:
"use strict"; const PLAYER_1_ELEMENT = document.querySelector(".player-1"); const PLAYER_2_ELEMENT = document.querySelector(".player-2"); const TOTAL_1_ELEMENT = document.querySelector(".total-1"); const TOTAL_2_ELEMENT = document.querySelector(".total-2"); const BTN_TRY_LUCK = document.querySelector(".top"); const BTN_RESET_LUCK = document.querySelector(".bottom"); const CURRENT_1_ELEMENT = document.querySelector(".borders-1"); const CURRENT_2_ELEMENT = document.querySelector(".borders-2"); const IMAGES_1 = document.querySelector(".images-1"); const IMAGES_2 = document.querySelector(".images-2") let player = [1,2]; // 用字符串拼接获取对应的全局变量 const targetImages = window[`IMAGES_${player[1]}`]; targetImages.classList.add("hidden"); // 条件判断(同样注意去掉.) if (targetImages.classList.contains("active")) { // 你的业务逻辑代码 }
⚠️ 注意:这种方式会依赖全局作用域,代码可读性差,容易引发变量冲突,仅适合临时修改,长期维护优先选方案1。
额外注意
classList.contains()方法的参数是类名本身,不要加.,比如写contains("active")而不是contains(".active"),这也是常见的错误点。
内容的提问来源于stack exchange,提问作者Cyber Venom
相关产品推荐
相关产品推荐

