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

与显示对象的格式相同。


当前回答

简单使用

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

其他回答

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

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

在NodeJS中,您可以使用util.inspect(obj)打印对象。请务必说明深度,否则只能打印出对象的浅层。

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

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

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

试试这个:

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

输出: