栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript数据格式/漂亮打印机

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript数据格式/漂亮打印机

我写了一个函数来以可读的形式转储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$/, "");}

选择带有递归调用的行上的缩进,然后在此行之后切换注释行,以支撑样式。

…我看到您整理了自己的版本,很好。参观者将有选择。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437088.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号