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

与显示对象的格式相同。


当前回答

使用此项:

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

其他回答

在控制台中显示对象的另一种方法是使用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对象的美化字符串的东西,请查看https://github.com/fresheneesz/beautinator . 例如:

var result = beautinator({ "font-size": "26px","font-family": "'Open Sans', sans-serif",color: "white", overflow: "hidden",padding: "4px 4px 4px 8px",Text: { display: "block", width: "100%","text-align": "center", "padding-left": "2px","word-break": "break-word"}})
console.log(result)

结果如下:

{ "font-size": "26px",
  "font-family": "'Open Sans', sans-serif",
  color: "white", overflow: "hidden",
  padding: "4px 4px 4px 8px",
  Text: { display: "block", width: "100%",
          "text-align": "center", "padding-left": "2px",
          "word-break": "break-word"
  }
}

如果对象中有函数,它甚至可以工作。

简单使用

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);

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

console.log()在调试对象方面做得很好,但如果您希望将对象打印到页面内容中,这里是我提出的模仿PHP print_r()功能的最简单方法。很多其他答案都想重新发明轮子,但在JavaScript的JSON.stringify()和HTML的<pre>标记之间,你可以得到你想要的东西。

var obj={name:'名称',联系人:{email:'thename@gmail.com',电话:'123456789'};$('body').append('<pre>'+JSON.stringify(obj,null,4)+'</pre>');<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script>