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

我的create_box函数参数为何会随机变为undefined?

问题分析与修复

核心问题1:数组操作顺序错误

你先调用array_of_cells.splice(random_number,1)删除了目标元素,之后再去访问array_of_cells[random_number]——此时这个索引对应的元素要么是原数组中该位置的下一个元素(如果random_number不是最后一位),要么直接是undefined(如果random_number是原数组最后一个索引),这就是参数变成undefined的根本原因。

核心问题2:随机数计算的优先级错误

Math.floor(Math.random() * array_of_cells.length-1)中减法运算优先级高于乘法,实际会先计算array_of_cells.length-1,再和Math.random()相乘,导致随机数范围错误,索引取值逻辑混乱。

修复后的代码

function go(n_columns,n_rows){
    let array_of_cells=[];
    let number_columns=n_columns+1;
    let number_rows=n_rows+1;
    for(let columns=1;columns<number_columns;columns++){
        for(let rows=1;rows<number_rows;rows++){
            let obj={column:columns, row:rows};
            array_of_cells.push(obj);
        }
    }

    // 修正循环条件,确保所有元素都能被处理
    while(array_of_cells.length > 0){
        // 计算正确的随机索引:0到当前数组长度-1之间
        let random_number=Math.floor(Math.random() * array_of_cells.length);
        // 先取出要处理的元素,再执行删除操作
        const targetCell = array_of_cells[random_number];
        array_of_cells.splice(random_number,1);
        // 传入取出的元素给create_box
        create_box(targetCell);
        console.log(array_of_cells);
    }

    function create_box(position){
        console.log(position.row)
        let box=document.createElement("div");
        document.querySelector("#wrapper").appendChild(box);
        box.style.backgroundColor="red";
        box.style.gridArea = `${position.row} / ${position.column}`;
    }
}
go(10, 10);

额外说明

原循环条件while(1 < array_of_cells.length)会导致数组最后一个元素永远无法被处理(当数组长度为1时,1 < 1不成立,循环终止)。修复后改为array_of_cells.length > 0,确保所有网格位置都能被随机填充。

内容的提问来源于stack exchange,提问作者Linnéa Andersson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:30:53