如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
假设对象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
希望这有帮助!
其他回答
在控制台中显示对象的另一种方法是使用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));
我使用了pagewil的打印方法,效果非常好。
这是我的略微扩展版本,带有(草率的)缩进和不同的prop/ob分隔符:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};
我在项目中总是使用一个小助手函数,通过控制台进行简单、快速的调试。灵感来自拉雅维尔。
/**
* @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');
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。
试试看:
console.log(JSON.stringify(obj))
这将打印对象的字符串版本。因此,您将获得object的内容,而不是[object]作为输出。