JavaScript彩票号码匹配高亮出现位置匹配错误如何解决
现有代码存在的问题
- 错误将变量名作为字符串进行匹配,比如
"displayUserNum1".match(lotteryNumber7)实际是在匹配字符串"displayUserNum1"里有没有对应开奖号,根本没有用到用户输入的真实号码 - 号码匹配逻辑是强制按位置对应:只比对用户第1个号和开奖第1个号、用户第2个和开奖第2个,没有全局匹配所有开奖号
- 存在类名拼写错误:
highghtBonusWin多写了一个g,会导致样式不生效 - 代码冗余度高,用大量单独变量存储号码,后续维护难度大
修正方案
我们先把用户号码和开奖号码都存入数组,遍历匹配所有存在的相同号码,不需要按位置对应:
// 存储用户号码的DOM ID和输入值 const userNumIds = ["displayUserNum1", "displayUserNum2", "displayUserNum3", "displayUserNum4", "displayUserNum5", "displayUserNum6"] const userNums = [] // 获取用户输入 userNumIds.forEach((id, index) => { const num = window.prompt(`Enter your ${index+1} Number`) userNums.push(Number(num)) document.getElementById(id).innerHTML = num }) // 生成开奖号码,前6个为普通号,第7个为特别号 const lotteryDrawIds = ["draw1", "draw2", "draw3", "draw4", "draw5", "draw6", "bonus"] const lotteryNums = [] for(let i=0; i<7; i++) { const num = Math.floor(Math.random() * 10) + 1 lotteryNums.push(num) document.getElementById(lotteryDrawIds[i]).innerHTML = num } document.getElementById("bonus").classList.add("highlightBonus") const bonusNum = lotteryNums[6] const normalLotteryNums = lotteryNums.slice(0,6) // 匹配号码并高亮 userNums.forEach((num, index) => { const dom = document.getElementById(userNumIds[index]) // 先匹配特别号 if(num === bonusNum) { dom.classList.add("highlightBonusWin") } // 再匹配普通开奖号,不管位置 if(normalLotteryNums.includes(num)) { dom.classList.add("highlightWin") } }) const d = new Date(); document.getElementById("lmd").innerHTML = d;
优化说明
- 用数组存储号码和对应DOM ID,大幅减少冗余代码
- 取消按位置匹配逻辑,只要用户号码在开奖号码列表里存在就高亮
- 修复了原代码的类名拼写错误和变量名当字符串匹配的逻辑错误
- 同时支持普通中奖号码和特别奖号码的匹配高亮,两种样式可以叠加
内容的提问来源于stack exchange,提问作者Vimesh Perera
相关产品推荐
相关产品推荐

