如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?

与显示对象的格式相同。


当前回答

好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。

我想,对于大多数调试目的来说,这已经足够了。

其他回答

好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。

我想,对于大多数调试目的来说,这已经足够了。

使用此项:

console.log('print object: ' + JSON.stringify(session));

显示对象内容的一种简单方法是使用console.log,如下所示

console.log("Object contents are ", obj);

请注意,我没有使用“+”连接对象。如果我使用“+”,那么我将只得到If对象的字符串表示,类似于[Objectobject]。

在控制台中显示对象的另一种方法是使用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));

我总是使用console.log(“对象将是:”,obj,obj1)。这样我就不需要用JSON来解决字符串问题。对象的所有财产都将很好地展开。