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

遍历cardArray读取specials的desc属性报Uncaught TypeError问题

核心报错原因

你犯了两个直接导致报错的逻辑错误:

  1. 索引对应关系完全错误:你使用卡牌在cardArray中的随机下标i去读取specials数组的内容,但你实际应该用卡牌本身的special属性值作为specials的索引。
  2. 数组长度不匹配导致索引越界: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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:33:00