使用方形后退键设置嵌套对象的值将返回未定义

时间:2019-03-05 00:27:37

标签: 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中未定义? 任何提示都会很棒, 谢谢

2 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

尝试将您的对象定义为

var obj = new Object()

var obj = new Object();

function nestedValue(a, b) {
   obj[a] = b;
   console.log(obj);
   return obj;
}

nestedValue("fruit","apple");