【问题标题】:Node JS Undefined variable节点 JS 未定义变量
【发布时间】:2018-03-01 03:38:54
【问题描述】:

我有一个函数应该遍历 JSON 文件,获取值并将它们推送到新数组。

我在函数外声明了数组如下:

var output = [];

function get_json(jsonObj) {
    console.log("Out put => " + output);

    for (var x in jsonObj) {
        if (typeof (jsonObj[x]) == 'object') {
            get_json(jsonObj[x]);
        } else {
            output.push({
                key: x,
                value: jsonObj[x]
            });
            //console.log(output);
        }
    }
    return output;
}

上述函数被调用并传入json数据如下:

var result = get_json(jsonObj);

它应该返回一个包含值、键和值的数组。但是,当我将数据推送到函数时,我得到未定义的输出变量,因此它无法创建数组,从而导致失败。 如何声明数组?声明它的最佳位置是什么?

【问题讨论】:

  • 这对我来说似乎很好用。如果还有更多代码,也许您可​​以显示整个代码。此外,在函数外部声明数组使其成为全局数组,因此每次调用函数时,都会将新项目推送到已经存在的数组中。
  • 输出数组有问题。
  • @David 这个问题只会在你传递一个对象属性时出现,看起来 OP 没有处理嵌套的 get_json 调用的结果。
  • 这对我来说也很好,你能提供一个给出问题的示例 json。

标签: javascript arrays json node.js


【解决方案1】:

您正在尝试执行递归函数。您可以在函数内移动output 声明并在最后返回它,但不要忘记在每次迭代时填充它(即在此处使用concat 和push)。我更喜欢这个版本而不是全局变量,因为它更干净并且避免了你似乎有的冲突。

function get_json(jsonObj) {
  var output = [];

  for (var x in jsonObj) {
    if (typeof(jsonObj[x]) === 'object') {
      output = output.concat(get_json(jsonObj[x]));
    } else {
      output.push({
        key: x,
        value: jsonObj[x]
      });
    }
  }

  return output;
}

console.log(get_json({
  person: {
    name: 'John Doe',
    age: 26,
    stuff: [{
        name: 'Big Sword'
      },
      {
        name: 'Yoyo'
      }
    ]
  },
  city: 'New York'
}));

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2020-12-22
    • 1970-01-01
    相关资源
    最近更新 更多