如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
试试这个:
var object = this.window;
console.log(object,'this is window object');
输出:
其他回答
如果要使用alert打印对象,可以执行以下操作:
alert(“myObject是”+myObject.toSource());
它应该以字符串格式打印每个属性及其对应的值。
var output = '';
for (var property in object) {
output += property + ': ' + object[property]+'; ';
}
alert(output);
您还可以使用ES6模板文本概念以字符串格式显示JavaScript对象的内容。
alert(`${JSON.stringify(obj)}`);
常量对象={“name”:“John Doe”,“habbits”:“没有”,};警报(`${JSON.stringify(obj)}`);
使用本机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"
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