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

标签 javascript object nested

我正在尝试设置嵌套对象属性的值。在 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/

相关文章:

pointers - 如何检查嵌套指针中的值

javascript - 日期验证伪代码到 JavaScript

javascript - 如何在 Android WebView 中嵌入 Youtube 视频?

javascript - Wallabyjs - 不断收到 TypeError : 'undefined'

c++ - 如何在导入另一个库的库中修复 "invalid use of non-static member function"

python - 删除所有嵌套 block ,同时通过 python 单独保留非嵌套 block

javascript - 安装后尝试设置时出现 react 导航错误 - 元素类型无效

python - 如何删除Python中的旧引用?

javascript:通过增加 objectKeys 值来更新对象

css - 更少的可重用嵌套类