如何以字符串格式显示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));

其他回答

假设对象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

希望这有帮助!

var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

其中object是您的对象

或者您可以在chrome开发工具的“控制台”选项卡中使用此选项:

console.log(对象);

简单使用

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

您还可以使用ES6模板文本概念以字符串格式显示JavaScript对象的内容。

alert(`${JSON.stringify(obj)}`);

常量对象={“name”:“John Doe”,“habbits”:“没有”,};警报(`${JSON.stringify(obj)}`);

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>