如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
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.log("%o", obj);
试试看:
console.log(JSON.stringify(obj))
这将打印对象的字符串版本。因此,您将获得object的内容,而不是[object]作为输出。
简单使用
JSON.stringify(obj)
实例
var args_string = JSON.stringify(obj);
console.log(args_string);
Or
alert(args_string);
此外,注意javascript函数被视为对象。
作为补充说明:
实际上,您可以像这样分配新属性并访问它console.log或在警报中显示它
foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
假设对象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
希望这有帮助!
试试这个:
var object = this.window;
console.log(object,'this is window object');
输出: