如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。
其他回答
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。
功能:
var print = function(o){
var str='';
for(var p in o){
if(typeof o[p] == 'string'){
str+= p + ': ' + o[p]+'; </br>';
}else{
str+= p + ': { </br>' + print(o[p]) + '}';
}
}
return str;
}
用法:
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
例子:
http://jsfiddle.net/WilsonPage/6eqMn/
使用本机JSON.stringify方法。适用于嵌套对象,所有主要浏览器都支持此方法。
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
链接到Mozilla API参考和其他示例。
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
如果您遇到此Javascript错误
"Uncaught TypeError: Converting circular structure to JSON"
编号:在这些示例中,yourObj定义了要检查的对象。
首先,我最不喜欢但最常用的显示对象的方式:
这是显示对象内容的实际方式
console.log(yourObj)
将产生如下结果:
我认为最好的解决方案是查看对象关键点,然后查看对象值,如果您真的想查看对象的内容。。。
console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));
它将输出如下内容:(上图:存储在对象中的键/值)
如果您使用的是ECMAScript 2016或更高版本,还有一个新选项:
Object.keys(yourObj).forEach(e => console.log(`key=${e} value=${yourObj[e]}`));
这将产生整洁的输出:前面的回答中提到的解决方案:console.log(yourObj)显示了太多的参数,并且不是显示所需数据的最方便用户的方式。这就是为什么我建议分别记录键和值。
下一步:
console.table(yourObj)
有人在之前的评论中建议过这个,但它从来没有对我起过作用。如果它对其他人在不同的浏览器或其他东西上起作用,那就太好了!我仍将代码放在此处以供参考!将向控制台输出如下内容:
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