gpt4 book ai didi

javascript - 使用方形 backets 设置嵌套对象的值返回 undefined

转载 作者:行者123 更新时间:2023-11-30 19:45:23 25 4
gpt4 key购买 nike

我正在尝试设置嵌套对象属性的值。在 Jsbin 上,我的第一个案例运行良好。在我的本地代码 - 第二种情况 - 上,它失败了。我不明白为什么。

jsbin 片段:

var obj= {a:{}}
obj["a"]["b"]="bValue";
console.log(obj) // return a valid object

我的本​​地代码片段:

let userData = { a: {} }

function nestedValue(a, b) {
if (userData[a][b] === undefined) {
console.log("set a")
userData[a][b] = "here"
console.log("set b: ", userData[a][b]) // return undefined
}
}
nestedValue("fruit", "apple")

我想知道为什么第二种情况在 console.log 中返回 undefined?任何提示都会很棒,谢谢

最佳答案

let userData = {};

function nestedValue(a, b) {
if(!!userData[a] === undefined) {
userData[a] = {};
}

if (userData[a][b] === undefined) {
console.log("set a")
userData[a][b] = "here"
console.log("set b: ", userData[a][b]) // return undefined
}
}
nestedValue("fruit", "apple")

在上面的示例中,您使用的是 bracket 表示法,它将使用键的实际值。 fruit 在这种情况下。

因此它期望初始对象具有名为 fruit 的属性

var obj= { fruit :{}}

-

userData[a][b]

let userData = { fruit : {} } // will work for the above use case.

不等于

userData.a.[b]

let userData = { a : {} } // will work for the above use case.

关于javascript - 使用方形 backets 设置嵌套对象的值返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54993664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com