如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
看起来很简单。。。in无法解决这个问题,特别是当我们想要处理自定义、主机、本机或CSCOM对象之外的问题时。此外,我们正在讨论调试,谁知道我们何时何地需要它!
我的小型库可以处理以下对象:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
并呈现出丰富多彩的标识,如:
0,foo,'bar'0,loop2,'包含对索引0'0处的对象的循环引用,另一个,'object'1,a1,11,b1,'baz'1,loop1,'包含索引2'1,c1,'true'1,d1,''1,e1,[1,2]处的对象循环引用
但请看这里:
https://github.com/centurianii/jsdebughttp://jsfiddle.net/centurianii/92Cmk/36/
通过一些预防措施,甚至可以解析document.body!
其他回答
在控制台中显示对象的另一种方法是使用JSON.stringify。请查看以下示例:
var gandalf = {
"real name": "Gandalf",
"age (est)": 11000,
"race": "Maia",
"haveRetirementPlan": true,
"aliases": [
"Greyhame",
"Stormcrow",
"Mithrandir",
"Gandalf the Grey",
"Gandalf the White"
]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
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
我在项目中总是使用一个小助手函数,通过控制台进行简单、快速的调试。灵感来自拉雅维尔。
/**
* @param variable mixed The var to log to the console
* @param varName string Optional, will appear as a label before the var
*/
function dd(variable, varName) {
var varNameOutput;
varName = varName || '';
varNameOutput = varName ? varName + ':' : '';
console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}
用法
日(123.55);输出:
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
简单使用
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);
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。