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

俄罗斯方块游戏函数报错:TypeError: squares.splice is not a function

问题分析与解决

错误原因

squares.splice is not a function 这个错误说明**squares不是真正的数组**。通常是因为你用document.querySelectorAll()获取DOM元素集合时,得到的是NodeList(类数组对象),它不具备数组的splice方法。

解决步骤

1. 将squares转换为真正的数组

找到你定义squares的代码,比如:

const squares = document.querySelectorAll('.square');

把它改成以下两种方式之一,将NodeList转为数组:

// 方法1:使用Array.from()
const squares = Array.from(document.querySelectorAll('.square'));

// 方法2:使用扩展运算符
const squares = [...document.querySelectorAll('.square')];

2. 修正消除行的DOM同步逻辑

你当前的代码只移除了元素的taker类并修改数组,但页面上的DOM元素没有被移除或重排,会导致后续方块位置错乱,需要补充DOM操作:

function scoreBoard () {
    for (let i = 0; i < 199; i += width) {
        const rows = [i, i+1, i+2, i+3, i+4, i+5, i+6, i+7, i+8, i+9];

        if(rows.every(index => squares[index].classList.contains('taker'))) {
            score +=10;
            scoreDisplay.innerHTML = score;
            
            // 移除该行的DOM元素
            rows.forEach(index => {
                squares[index].remove();
            });
            
            // 从数组中移除该行元素
            squares.splice(i, width);
            
            // 在容器顶部添加新的空白方块(需替换为你的容器ID)
            const squareContainer = document.getElementById('square-container');
            for(let j=0; j<width; j++){
                const newSquare = document.createElement('div');
                newSquare.classList.add('square');
                squareContainer.prepend(newSquare);
            }
            
            // 更新squares数组,纳入新添加的空白方块
            squares.unshift(...Array.from(document.querySelectorAll('.square')).slice(0, width));
        }
    }
}

关键说明

  • 转数组后才能使用splice等数组方法操作元素集合。
  • 消除行时必须同步修改DOM:移除满行元素、添加新空白行到顶部,保证方块布局正确。
  • 最后要更新squares数组,把新添加的空白方块纳入,否则后续逻辑会出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:34:55