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

JS开发网站遇Uncaught TypeError:无法读取undefined的'mano'属性求助

问题分析与解决

错误定位

报错Uncaught TypeError: Cannot read properties of undefined (reading 'mano')指向scambiaCarta函数中读取mano属性的代码,根源是传入该函数的某个玩家对象为undefined,导致无法访问其属性。

触发原因

在eseguiTurnoCPU函数中,计算giocatorePrecedente的索引时缺少取模运算:

const giocatorePrecedente = giocatori[(turnoCorrente - 1 + giocatori.length)];

当turnoCorrente的值大于等于giocatori.length时,计算出的索引会超出数组范围,导致获取到undefined的玩家对象。比如giocatori.length为2、turnoCorrente为3时,计算结果为4,而giocatori[4]不存在,返回undefined。这个undefined传入scambiaCarta后,执行giocatore2.mano.push(cartaScambiata)就会触发报错。

修复代码

给giocatorePrecedente的索引加上取模运算,确保索引始终在数组合法范围内:

const giocatorePrecedente = giocatori[(turnoCorrente - 1 + giocatori.length) % giocatori.length];

额外优化建议

为避免类似异常,建议在scambiaCarta函数开头增加参数合法性校验,提前拦截非法输入:

function scambiaCarta(giocatore1, giocatore2) {
    // 新增参数校验
    if (!giocatore1?.mano || !giocatore2?.mano) {
        console.error("玩家对象不合法,无法执行换牌操作");
        return;
    }

    if (deveBloccareScambioCarta(giocatore1.mano[0])) {
        console.log(`${giocatore1.nome} ha il Re in mano. Cucù.`);
        return;
    }
    // 剩余代码保持不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:13:12