如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
其中object是您的对象
或者您可以在chrome开发工具的“控制台”选项卡中使用此选项:
console.log(对象);
其他回答
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
正如之前所说,我发现的最简单的方法是
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
使用此项:
console.log('print object: ' + JSON.stringify(session));
我总是使用console.log(“对象将是:”,obj,obj1)。这样我就不需要用JSON来解决字符串问题。对象的所有财产都将很好地展开。
简单使用
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);