如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
var output = '';
for (var property in object) {
output += property + ': ' + object[property]+'; ';
}
alert(output);
其他回答
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。
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.table来获得清晰的对象格式,所以假设您有这个对象:
const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};
您将看到一张整洁易读的表格,如下所示:
如果要打印用于调试的对象,请使用以下代码:
var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)
将显示:
注意:您只能记录对象。例如,这不起作用:
console.log('My object : ' + obj)
注意:您也可以在log方法中使用逗号,然后输出的第一行将是字符串,之后将呈现对象:
console.log('My object: ', obj);
您还可以使用ES6模板文本概念以字符串格式显示JavaScript对象的内容。
alert(`${JSON.stringify(obj)}`);
常量对象={“name”:“John Doe”,“habbits”:“没有”,};警报(`${JSON.stringify(obj)}`);