实现点击两个骰子投掷按钮累计总投掷次数的计数器问题
骰子计数器功能实现方案
原有代码问题修正
- 事件绑定写法错误:
document.getElementById("roll1")后多余的.document需要删除,绑定事件时回调函数不要加(),否则会在页面加载时直接执行函数,点击按钮反而不会触发逻辑 - 全局计数变量
numRolls没有初始化,直接累加会返回NaN - 缺少骰子投掷逻辑、
Array.prototype.map渲染表格逻辑、总投掷次数展示更新逻辑
完整实现代码
页面结构代码
<button id="roll1">单次投掷</button> <button id="roll1000">千次投掷</button> <p>累计总投掷次数:<span id="totalCount">0</span></p> <table border="1"> <thead> <tr> <th>投掷序号</th> <th>骰子点数</th> </tr> </thead> <tbody id="resultTbody"></tbody> </table>
逻辑代码
// 初始化全局变量 let numRolls = 0 // 存储所有投掷结果的数组 let allRollResults = [] const totalCountDom = document.getElementById('totalCount') const resultTbodyDom = document.getElementById('resultTbody') // 生成单次骰子点数(1-6随机整数) function getDicePoint() { return Math.floor(Math.random() * 6) + 1 } // 单次投掷逻辑 function rollOnce() { allRollResults.push(getDicePoint()) numRolls += 1 updatePage() } // 千次投掷逻辑 function rollThousandTimes() { // 批量生成1000次投掷结果 const batchResult = Array.from({length: 1000}, getDicePoint) allRollResults.push(...batchResult) numRolls += 1000 updatePage() } // 统一更新页面视图 function updatePage() { // 更新总次数展示 totalCountDom.textContent = numRolls // 用Array.prototype.map生成表格行内容 const tableHtml = allRollResults.map((point, index) => ` <tr> <td>${index + 1}</td> <td>${point}</td> </tr> `).join('') resultTbodyDom.innerHTML = tableHtml } // 绑定按钮点击事件 document.getElementById('roll1').addEventListener('click', rollOnce) document.getElementById('roll1000').addEventListener('click', rollThousandTimes)
实现说明
- 用
Array.from批量生成千次投掷结果,写法更简洁易读 - 所有视图更新逻辑统一封装在
updatePage方法中,避免重复编码 - 表格渲染通过
map遍历投掷结果数组生成DOM字符串,一次性插入页面,减少频繁DOM操作的性能损耗
内容的提问来源于stack exchange,提问作者HelpWantedSign
相关产品推荐
相关产品推荐

