【问题标题】:How to inspect Javascript Objects如何检查 Javascript 对象
【发布时间】:2011-07-18 11:09:22
【问题描述】:

如何检查警告框中的对象?通常警告对象只会抛出节点名:

alert(document);

但是我想在alert框中获取对象的属性和方法。如果可能的话,我怎样才能实现这个功能?或者有其他建议吗?

特别是,我正在为无法使用 console.log 和 Firebug 的生产环境寻找解决方案。

【问题讨论】:

  • 在 firefox 或 chrome 上做 console.log
  • 我很困惑。在生产环境中,您有实际用户,对吗?那么你为什么要抛出带有对象属性的警报呢?也许更好的解决方案是将对象序列化并将其记录在文件中或发送电子邮件?
  • 也许他/她需要警报作为工具,但实际功能需要做其他事情。他/她可能想要这样做的原因有很多,例如显示统计信息或发生错误,或者通过简单地将对象传递给他/她用来检查对象的任何对象来同时进行。
  • 有时JSON.stringify 很有帮助。

标签: javascript object inspect


【解决方案1】:

使用您的控制台:

console.log(object);

或者,如果您正在检查 html dom 元素,请使用 console.dir(object)。示例:

let element = document.getElementById('alertBoxContainer');
console.dir(element);

或者,如果你有一个 js 对象数组,你可以使用:

console.table(objectArr);

如果你输出很多 console.log(objects) 你也可以写

console.log({ objectName1 });
console.log({ objectName2 });

这将帮助您标记写入控制台的对象。

【讨论】:

  • 这些显示的值会实时动态变化,这可能会误导调试目的
  • 在 chrome 中使用您的控制台首选项并单击保留日志。现在,即使您的脚本将您重定向到另一个页面,您的控制台也不会被清除。
  • 似乎这个问题与 Firefox 相关,因为在 Chrome 中,除非您重新使用 console.log(),否则显示的值仍然存在。您可能会建议迁移到 Chrome,但有时您正在测试浏览器功能的可用性。无论如何,感谢您提供可能有用的提示。
  • 我不能使用console,因为我正在使用样式stackoverflow.com/q/7505623/1480391,它不兼容
【解决方案2】:

使用 console.dir(object) 和 Firebug 插件

【讨论】:

  • 这为我提供了最完整、最有用的信息。谢谢。
  • 我不知道console.dir 功能。我无法弄清楚为什么我不能再在 Firebug 中查看完整的对象。现在已经为我整理好了。谢谢!
  • 我想知道这个除了显示方便之外,还有没有其他比console.log的优点
【解决方案3】:

这是我的更具可读性的对象检查器。因为代码需要很长时间才能在这里写下来,你可以在http://etto-aa-js.googlecode.com/svn/trunk/inspector.js下载它

这样使用:

document.write(inspect(object));

【讨论】:

  • 通常是这种情况(这绝对是官方指导——不要发布链接),OTOH,对于像这样的版本,它可能有点好,因为你知道你'重新总是要查看最新的代码,而不是几年前发布的一些陈旧的东西,可能不再工作了...... - 此外,粘贴到文字墙中的那块巨大的代码看起来非常糟糕所以答案... -- 题外话: 如果 SO 上有一种方法可以为代码添加类似“剧透”的标签并能够链接到外部源并使其自动运行,那就太好了更新(如果可能),
【解决方案4】:

alert(JSON.stringify(object)) 使用现代浏览器怎么样?

如果是TypeError: Converting circular structure to JSON,这里有更多选项:How to serialize DOM node to JSON even if there are circular references?

文档:JSON.stringify() 提供有关格式化或美化输出的信息。

【讨论】:

  • +1 好建议。我想补充一下,他可以使用 jsonview (jsonviewer.stack.hu) 很好地查看它。
  • 如果您也希望它的格式也很好,您可以调用:alert(JSON.stringify(object, null, 4),其中4 是用于缩进的空格数。
  • 这给了我“未定义”作为输出。我正在尝试调试业力测试。
  • 这种方法有一些注意事项。 OP 说她想检查对象的方法。 stringify 不会显示方法:JSON.stringify({f: ()=>{}}) => "{}"。此外,如果对象实现了toJSON 方法,您将获得该方法返回的内容,如果您想检查对象,这将是无用的:JSON.stringify({toJSON: () => 'nothin'}) => '"nothin"'
【解决方案5】:

这是对 Christian 出色答案的公然抄袭。我只是让它更具可读性:

/**
 * objectInspector digs through a Javascript object
 * to display all its properties
 *
 * @param object - a Javascript object to inspect
 * @param result - a string of properties with datatypes
 *
 * @return result - the concatenated description of all object properties
 */
function objectInspector(object, result) {
    if (typeof object != "object")
        return "Invalid object";
    if (typeof result == "undefined")
        result = '';

    if (result.length > 50)
        return "[RECURSION TOO DEEP. ABORTING.]";

    var rows = [];
    for (var property in object) {
        var datatype = typeof object[property];

        var tempDescription = result+'"'+property+'"';
        tempDescription += ' ('+datatype+') => ';
        if (datatype == "object")
            tempDescription += 'object: '+objectInspector(object[property],result+'  ');
        else
            tempDescription += object[property];

        rows.push(tempDescription);
    }//Close for

    return rows.join(result+"\n");
}//End objectInspector

【讨论】:

    【解决方案6】:

    有几种方法:

     1. typeof tells you which one of the 6 javascript types is the object. 
     2. instanceof tells you if the object is an instance of another object.
     3. List properties with for(var k in obj)
     4. Object.getOwnPropertyNames( anObjectToInspect ) 
     5. Object.getPrototypeOf( anObject )
     6. anObject.hasOwnProperty(aProperty) 
    

    在控制台上下文中,有时 .constructor 或 .prototype 可能有用:

    console.log(anObject.constructor ); 
    console.log(anObject.prototype ) ; 
    

    【讨论】:

      【解决方案7】:

      for-in 循环用于对象或数组中的每个属性。您可以使用此属性获取该值并对其进行更改。

      注意:私有属性不可用于检查,除非您使用“间谍”;基本上,您覆盖对象并编写一些代码,在对象的上下文中执行 for-in 循环。

      对于 in 看起来像:

      for (var property in object) loop();
      

      一些示例代码:

      function xinspect(o,i){
          if(typeof i=='undefined')i='';
          if(i.length>50)return '[MAX ITERATIONS]';
          var r=[];
          for(var p in o){
              var t=typeof o[p];
              r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+'  ') : o[p]+''));
          }
          return r.join(i+'\n');
      }
      
      // example of use:
      alert(xinspect(document));
      

      编辑:前段时间,我写了自己的inspector,如果你有兴趣,我很乐意分享。

      编辑 2:好吧,我还是写了一个。

      【讨论】:

      • 应该以某种方式防止递归。带有一些内部 html 渲染器 ID 的哈希(字典)?对于新手来说,将此检查推送到代码中可能很有用。
      • @Nakilon 我一直对无限递归提出质疑,尤其是在 PHP 中。有两种方法可以解决这个问题:使用深度参数,或者修改哈希并添加您自己的属性,用于检查递归。深度一可能更安全。
      • 我更喜欢这个版本的第 7 行。它看起来有点像 ruby​​ 并且做了一些不错的空格 r.push(i+'"'+p+'" => '+(t=='object' ? '{\n'+xinspect(o[p],i+ ' ')+('\n' + i + '},') : o[p]+''));
      • 那段代码完全破坏了 iPhone 上的 Safari Mobile。我会选择下面的 JSON.stringify 解决方案以获得更安全的替代方案。
      • 这件事让 safari 崩溃,chrome 检查对象,不推荐。
      【解决方案8】:
      var str = "";
      for(var k in obj)
          if (obj.hasOwnProperty(k)) //omit this test if you want to see built-in properties
              str += k + " = " + obj[k] + "\n";
      alert(str);
      

      【讨论】:

      • console.log() 是怎么做的? :)
      • 使用 Firefox 或 Chrome。获取 Firefox 的 Firebug。必须有
      • 我是在讽刺。 OP 专门要求提供 JS 代码,除非您建议他深入研究 firebug/fox/chrome,否则我不知道他会在哪里找到答案。
      猜你喜欢
      • 2021-08-15
      • 2010-09-27
      • 2020-11-12
      • 2012-06-26
      • 2011-08-22
      • 2016-04-10
      • 2017-12-10
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多