我写了一个函数来以可读的形式转储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$/, "");}选择带有递归调用的行上的缩进,然后在此行之后切换注释行,以支撑样式。
…我看到您整理了自己的版本,很好。参观者将有选择。



