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

JavaScript:从对象值获取键及对象字面量键名解析异常问题排查

问题原因及解决方法

原因

在JavaScript对象字面量里,直接写employeeCountryName: employeeCountryCode时,冒号左侧的内容会被当作字符串字面量处理,而不是读取变量的值。所以这里的键名会直接变成字符串"employeeCountryName",而非变量employeeCountryName存储的实际内容。

解决方法

要让变量的值成为对象的键名,需要使用计算属性名语法,把变量放在方括号[]中:

const newCountryList = {
    [employeeCountryName]: employeeCountryCode
};

这样JavaScript会先计算employeeCountryName的取值,再将这个值作为键名。

额外提示

你代码里还有个小细节:employeeCountryCode的值是"GBP",但countryList中对应的值是"GBR",所以getKey函数会返回undefined。如果想得到预期的"United Kingdom",需要把employeeCountryCode改为"GBR"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:42:14