俄罗斯方块开发遇Uncaught TypeError错误,求修复方案
修复俄罗斯方块游戏的两个Uncaught TypeError错误
嘿,我来帮你搞定这两个TypeError问题,都是DOM选择或者数组索引的小疏忽,咱们一步步来修复:
错误1:Cannot read property 'forEach' of undefined(draw/undraw代码段)
这个错误是因为current变量在某些场景下变成了无效值,或者我们访问了超出grid范围的方块索引。咱们这样修复:
重置旋转状态:在生成新方块时,把旋转状态重置为0,避免沿用之前的旋转值导致索引越界。修改
freeze函数:function freeze() { if(current.some(index => { const squareIndex = currentPosition + index + width; return squareIndex < squares.length && squares[squareIndex].classList.contains('taken'); })) { current.forEach(index => { const squareIndex = currentPosition + index; if (squareIndex < squares.length) { squares[squareIndex].classList.add('taken') } }) // 重置新方块的旋转状态 random = nextRandom nextRandom = Math.floor(Math.random() * theTetrominoes.length) currentRotation = 0 // 新增这行,确保从初始旋转开始 current = theTetrominoes[random][currentRotation] currentPosition = 4 draw() displayShape() } }添加安全检查:在
draw和undraw函数里,先确保current是有效数组,同时避免访问超出squares范围的索引:// 修改draw函数 function draw() { if (!current || !Array.isArray(current)) return; current.forEach(index => { const squareIndex = currentPosition + index; if (squareIndex >= 0 && squareIndex < squares.length) { squares[squareIndex].classList.add('tetromino') } }) } // 修改undraw函数 function undraw() { if (!current || !Array.isArray(current)) return; current.forEach(index => { const squareIndex = currentPosition + index; if (squareIndex >= 0 && squareIndex < squares.length) { squares[squareIndex].classList.remove('tetromino') } }) }
错误2:Cannot read property 'classList' of undefined(classList.add('tetromino')处)
这个问题是mini-grid的选择器写错了!你用了document.querySelectorAll('mini-grid div'),但mini-grid是类名,不是HTML标签,需要加.来指定类选择器:
// 把原来的代码修改为: const displaySquares = document.querySelectorAll('.mini-grid div')
如果不加.,浏览器会去找名为<mini-grid>的标签,而不是class为mini-grid的容器,导致displaySquares是空数组,访问里面的元素自然会得到undefined。
额外的潜在问题修复
还有一个容易踩坑的点:在freeze函数的判断条件里,当方块落到最底部时,currentPosition + index + width会超出squares数组的长度,导致访问undefined元素。上面修改的freeze函数已经包含了这个检查,确保只在索引有效时才判断taken类。
最后别忘了检查你的HTML结构:.grid容器里需要有足够的div元素(比如20行×10列=200个),否则squares数组长度不够也会导致索引越界错误。
内容的提问来源于stack exchange,提问作者StacksOnStacks
相关产品推荐
相关产品推荐

