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

与显示对象的格式相同。


当前回答

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

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

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

其他回答

我在项目中总是使用一个小助手函数,通过控制台进行简单、快速的调试。灵感来自拉雅维尔。

/**
 * @param variable mixed  The var to log to the console
 * @param varName string  Optional, will appear as a label before the var
 */
function dd(variable, varName) {
    var varNameOutput;

    varName = varName || '';
    varNameOutput = varName ? varName + ':' : '';

    console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}

用法

日(123.55);输出:

var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj'); 

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

要使用Node.js打印带有颜色的完整对象,请执行以下操作:

console.dir(object, {depth: null, colors: true})

颜色当然是可选的,“depth:null”将打印整个对象。

浏览器似乎不支持这些选项。

参考文献:

https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

https://nodejs.org/api/console.html#console_console_dir_obj_options

试试这个:

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

输出:

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