代码之家  ›  专栏  ›  技术社区  ›  Webwoman

使用方形背景设置嵌套对象的值返回未定义

  •  1
  • Webwoman  · 技术社区  · 6 年前

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

    我想知道为什么第二个案例返回的是未定义的控制台日志? 任何暗示都很好, 谢谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   Sushanth --    6 年前

    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

    所以它期望初始对象的属性为 水果

    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.
    
        2
  •  0
  •   Jr Mendoza    6 年前

    var obj = new Object()
    

    var obj = new Object();
    
    function nestedValue(a, b) {
       obj[a] = b;
       console.log(obj);
       return obj;
    }
    
    nestedValue("fruit","apple");