【发布时间】:2019-10-06 21:03:07
【问题描述】:
我正在尝试访问 Javascript 对象中键的值。我的对象目前看起来像:
const options = {
"account.country": getCountry,
"account.phone": getPhone,
}
当我console.log(options) 时,它显示整个对象。但是,当我尝试时
console.log(options.account) // undefined,
console.log(options.account.country) // error.
我不明白为什么。我也试过了:
const parsedObj = JSON.parse(options);
console.log(parsedObj);
但它只是返回
'JSON 中位置 1 的意外标记 o'
【问题讨论】:
-
getCountry和getPhone是什么? -
options["account.country"]? -
你不应该 JSON.parse 一个对象。
-
关键是“account.country”..你必须使用括号表示法。
options['account.country']。至于JSON.parse... 那是用来解析 JSON 字符串的。如果要将 JS 对象转换为 JSON,请使用JSON.stringify()
标签: javascript object