代码之家  ›  专栏  ›  技术社区  ›  Aree Vanier

Javascript JSON未知行为

  •  0
  • Aree Vanier  · 技术社区  · 6 年前

    我试图设置JSON对象属性的值,但是当我运行 Object.property = value 整个JSON对象将替换为字符串 229,

    for(var i=0; i<config["profiles"].length; i++){
        profile = config["profiles"][i];
        out = {
          "name":profile["name"],
          "version":profile["version"].replace(/_/g, "."),
          "mods":null,
          "saves":null
        }
        console.log(out)
        out.mods = getMods(profile);
        console.log(out)
        console.log(getSaves(profile))
        out.saves = getSaves(profile);
        console.log(out)
        profiles.push(out);
    }
    return profiles;
    

    前2名 console.log(out) 调用按预期返回正确的JSON对象。

    console.log(getSaves(profile)) 打印以下内容:

    [ { name: 'Hard Career ',
        mode: 'CAREER',
        funds: '275,520',
        science: '229',
        reputation: '721',
        flights: '20' },
      { name: 'Sandbox ',
        mode: 'SANDBOX',
        funds: 0,
        science: 0,
        reputation: 0,
        flights: '12' } ]
    

    但是,打印后 out.saves = getSaves(profile) 打印以下内容: 229, .

    更复杂的是,这只发生在 config["profiles"] 数组。

    提前谢谢!

    1 回复  |  直到 6 年前
        1
  •  2
  •   Mark    6 年前

    您应该使用以下命令声明变量 let profile =

    如果你不这么做 profile out 将是全局变量,这意味着每次通过 for

    let profile = config["profiles"][i];
    let out = {
      "name":profile["name"],
      "version":profile["version"].replace(/_/g, "."),
      "mods":null,
      "saves":null
    }
    

    应该有帮助。