如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?

与显示对象的格式相同。


当前回答

试试看:

console.log(JSON.stringify(obj))

这将打印对象的字符串版本。因此,您将获得object的内容,而不是[object]作为输出。

其他回答

在NodeJS中,您可以使用util.inspect(obj)打印对象。请务必说明深度,否则只能打印出对象的浅层。

这里有一种方法:

console.log("%o", obj);

假设对象obj={0:'John',1:'Foo',2:'Bar'}

打印对象的内容

for (var i in obj){
    console.log(obj[i], i);
}

控制台输出(Chrome DevTools):

John 0
Foo 1
Bar 2

希望这有帮助!

Javascript函数

<script type="text/javascript">
    function print_r(theObj){ 
       if(theObj.constructor == Array || theObj.constructor == Object){ 
          document.write("<ul>") 
          for(var p in theObj){ 
             if(theObj[p].constructor == Array || theObj[p].constructor == Object){ 
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); 
                document.write("<ul>") 
                print_r(theObj[p]); 
                document.write("</ul>") 
             } else { 
                document.write("<li>["+p+"] => "+theObj[p]+"</li>"); 
             } 
          } 
          document.write("</ul>") 
       } 
    } 
</script>

正在打印对象

<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script> 

通过Javascript中的print_r

console.dir(对象):

显示指定JavaScript对象的财产的交互式列表。此列表允许您使用公开三角形来检查子对象的内容。

请注意,console.dir()特性是非标准的。查看MDN Web文档