遍历cardArray读取specials的desc属性报Uncaught TypeError问题
核心报错原因
你犯了两个直接导致报错的逻辑错误:
- 索引对应关系完全错误:你使用卡牌在
cardArray中的随机下标i去读取specials数组的内容,但你实际应该用卡牌本身的special属性值作为specials的索引。 - 数组长度不匹配导致索引越界:
cardArray共有6个元素(下标范围05),而`specials`数组只有5个元素(下标范围04),当随机抽到下标为5的saboteur卡牌时,specials[5]为undefined,读取desc属性就会抛出你遇到的类型错误。
额外提醒:你当前配置的
saboteur和barricade卡牌的special属性值都是3,会共用同一条特殊描述,如果你需要两者有不同的描述,需要调整special取值并补充specials数组的对应项。
其他可修复问题
- 打印行括号位置错误:原代码
console.log("spe: "+i+" "+cardArray[i]['name'])+": "+specials[i]['desc']的console.log右括号提前闭合,拼接逻辑完全错位。 - 抽卡次数不足:你用
$.each(cardArray, ...)遍历,最多只会执行6次循环,永远无法实现抽9张卡的需求。 - 样式语法错误:边框色值写了两个
#,应为#660066。 - 存在重复的样式设置逻辑。
修正后代码示例
let checker = 0; let title = ''; const handCardCount = 9; // 用while循环实现抽9张卡的需求 while(checker < handCardCount) { // 随机抽取卡牌 const cardIndex = Math.floor(Math.random() * cardArray.length); const currentCard = cardArray[cardIndex]; const specialVal = parseInt(currentCard.special); console.log(`each${cardIndex}:${currentCard.name} sp:${specialVal}`) // 拼接标题 if(specialVal > 0) { // 用special属性值读取specials数组,而不是卡牌下标 const specialDesc = specials[specialVal].desc; console.log(`spe: ${cardIndex} ${currentCard.name}: ${specialDesc}`) title = `${currentCard.name}: ${specialDesc}` } else { console.log(`nonsp: ${cardIndex} ${currentCard.name}`) title = currentCard.name } // 生成卡牌元素 const tCard = $(`<div class="cardContainer" title="${title}" data-id="${cardIndex}">${currentCard.damage}</div>`) // 统一设置背景 tCard.css('background', `url("${currentCard.img}")`) // 单独设置特殊边框 if(specialVal === 1) { tCard.css('border','2px dashed #660066') } $("#area_myCards").append(tCard) title = '' checker++ }
内容的提问来源于stack exchange,提问作者dux0r
相关产品推荐
相关产品推荐

