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

与显示对象的格式相同。


当前回答

如果要打印用于调试的对象,请使用以下代码:

var obj = {
  prop1: 'prop1Value',
  prop2: 'prop2Value',
  child: {
    childProp1: 'childProp1Value',
  },
}
console.log(obj)

将显示:

注意:您只能记录对象。例如,这不起作用:

console.log('My object : ' + obj)

注意:您也可以在log方法中使用逗号,然后输出的第一行将是字符串,之后将呈现对象:

console.log('My object: ', obj);

其他回答

它在浏览器中不起作用,您可能只需要在您希望获得对象的有效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 }))

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

如果单击表列,可以对表进行排序。

您还可以选择要显示的列:

console.table(obj, ['firstName', 'lastName']);

您可以在此处找到有关console.table的更多信息

如果要使用alert打印对象,可以执行以下操作:

alert(“myObject是”+myObject.toSource());

它应该以字符串格式打印每个属性及其对应的值。

如果要打印对象的全长,可以使用

console.log(require('util').inspect(obj,{showHidden:false,depth:null})

如果要通过将对象转换为字符串来打印该对象,则

console.log(JSON.stringify(obj));