错误 Javascript 中无效的速记属性初始值设定项

时间:2021-06-19 07:13:04

标签: javascript ecmascript-2020

let will_pokemon = {
    pikachu: {
        species: 'Mouse pokemon',
        height: 0.4,
        weight: 5
    }
}

let samson_pokemon = {
    raichu = {
        species: 'Rare pokemon',
        height: 0.8,
        weight: 12
    }
}

let weight4 = samson_pokemon?.pikachu?.weight //check either object property available if not will be undefined

console.log(weight4)

为什么我在 Chrome 浏览器上运行时出现错误 Invalid shorthand property initializer?

2 个答案:

答案 0 :(得分:1)

不要在 object literals 中使用“=”。应该是 raichu : {

let samson_pokemon = {
    raichu : {
        species: 'Rare pokemon',
        height: 0.8,
        weight: 12
    }
}

答案 1 :(得分:0)

你可以这样做。

let weight4 = (typeof samson_pokemon !== 'undefined') ? samson_pokemon.pikachu : samson_pokemon.weight;