我写了一个函数来以可读的形式转储一个 JS 对象,虽然输出没有缩进,但添加它应该不会太难:我从我为 Lua 制作的一个函数中制作了这个函数(它要复杂得多) 处理了这个缩进问题。
这是“简单”版本:
function DumpObject(obj)
{
  var od = new Object;
  var result = "";
  var len = 0;
  for (var property in obj)
  {
    var value = obj[property];
    if (typeof value == 'string')
      value = "'" + value + "'";
    else if (typeof value == 'object')
    {
      if (value instanceof Array)
      {
        value = "[ " + value + " ]";
      }
      else
      {
        var ood = DumpObject(value);
        value = "{ " + ood.dump + " }";
      }
    }
    result += "'" + property + "' : " + value + ", ";
    len++;
  }
  od.dump = result.replace(/, $/, "");
  od.len = len;
  return od;
}
我会考虑改进一下。
注 1:要使用它,请执行od = DumpObject(something)并使用 od.dump。令人费解,因为我也想要 len 值(项目数)用于另一个目的。使函数只返回字符串是微不足道的。
注 2:它不处理引用中的循环。
编辑
我做了缩进的版本。
function DumpObjectIndented(obj, indent)
{
  var result = "";
  if (indent == null) indent = "";
  for (var property in obj)
  {
    var value = obj[property];
    if (typeof value == 'string')
      value = "'" + value + "'";
    else if (typeof value == 'object')
    {
      if (value instanceof Array)
      {
        // Just let JS convert the Array to a string!
        value = "[ " + value + " ]";
      }
      else
      {
        // Recursive dump
        // (replace "  " by "\t" or something else if you prefer)
        var od = DumpObjectIndented(value, indent + "  ");
        // If you like { on the same line as the key
        //value = "{\n" + od + "\n" + indent + "}";
        // If you prefer { and } to be aligned
        value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
      }
    }
    result += indent + "'" + property + "' : " + value + ",\n";
  }
  return result.replace(/,\n$/, "");
}
在递归调用的行上选择缩进,然后通过在此行之后切换注释行来支持样式。
...我看到你掀起了自己的版本,这很好。游客将有选择。