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

解决SyntaxError ts(1351)报错:访问API返回数字开头属性问题

报错根因

SyntaxError: identifier starts immediately after numeric literal ts(1351) 报错的本质是 JavaScript 的语法限制:使用点语法访问对象属性时,属性名必须符合标准标识符命名规则,即不能以数字开头、不能包含特殊运算符/分隔符等。你当前需要访问的028304b866cc47d18c08e902edfcb4c6是数字开头的字符串类型键,不符合点语法的要求,因此触发语法错误。

可行解决方案

直接改用方括号语法访问该属性即可,方括号语法支持传入任意字符串作为属性名,不受标识符命名规则限制,不需要修改后端返回的键名。

修复后的渲染代码示例

const generateHtml = (data) => {
    console.log(data)
    // 数字开头的键用方括号包裹成字符串形式访问
    const profile = data.profiles['028304b866cc47d18c08e902edfcb4c6']
    const html = `
        <h2 class="" >${profile.data.display_name}</h2>
        <div class="name">${profile.cute_name}</div>
        <div class="armor">${profile.items.armor_set}</div>
        <div>Rarity: ${profile.items.armor_set_rarity}</div>
    `
    const playerprofilebox = document.querySelector('#object')
    playerprofilebox.innerHTML = html
}

额外适配方案

如果这个profiles下的键是动态生成的、不是固定值,你可以不用硬编码键名,通过Object.values直接取对应属性即可,示例如下:

const generateHtml = (data) => {
    console.log(data)
    // 取profiles下的第一个属性值,适配动态键场景
    const profile = Object.values(data.profiles)[0]
    const html = `
        <h2 class="" >${profile.data.display_name}</h2>
        <div class="name">${profile.cute_name}</div>
        <div class="armor">${profile.items.armor_set}</div>
        <div>Rarity: ${profile.items.armor_set_rarity}</div>
    `
    const playerprofilebox = document.querySelector('#object')
    playerprofilebox.innerHTML = html
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:54:04