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

与显示对象的格式相同。


当前回答

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

其他回答

使用本机JSON.stringify方法。适用于嵌套对象,所有主要浏览器都支持此方法。

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

链接到Mozilla API参考和其他示例。

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

如果您遇到此Javascript错误

"Uncaught TypeError: Converting circular structure to JSON"

正如之前所说,我发现的最简单的方法是

var getPrintObject=function(object)
{
    return JSON.stringify(object);
}

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

它在浏览器中不起作用,您可能只需要在您希望获得对象的有效JS表示而不是JSON的情况下使用它。它只运行节点内联求值

var execSync = require('child_process').execSync

const objectToSource = (obj) =>
  execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })

console.log(objectToSource({ a: 1 }))

试试这个:

var object = this.window;
console.log(object,'this is window object');

输出: