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

与显示对象的格式相同。


当前回答

最简单的答案

我很惊讶,这没有一个更简单的答案,只是一群人重复着完全相同的2件事,还有一些人用不可读的代码。。。

干得好。如果您只需要将对象作为字符串(无嵌套级别):

function prettyStringifyObject(obj: Record < any, any > ) {
  let result = ''
  for (const key in obj) {
    result = `${result}${result !== '' ? ', ' : ''}${key}: ${Array.isArray(obj[key]) ? `[${obj[key]}]` : obj[key]}`
  }
  return `{${result}}`
}

测验

使用测试

const someTestObject = {
  data: [1, 2, 3, "4"],
  aString: "awdasdyhblhyb",
  aBoolean: true,
  aNumber: 50,
  aNull: null
  aNestedObject: {
    someOtherData: [],
    isNested: true
  }
}

console.log(prettyStringifyObject(someTestObject))

结果:

"{data: [1,2,3,4], aString: awdasdyhblhyb, aBoolean: true, aNumber: 50, aNull: null, aNestedObject: [object Object]}"

你可以看看我在这里做的JSFiddle

其他回答

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

好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。

我想,对于大多数调试目的来说,这已经足够了。

我使用了pagewil的打印方法,效果非常好。

这是我的略微扩展版本,带有(草率的)缩进和不同的prop/ob分隔符:

var print = function(obj, delp, delo, ind){
    delp = delp!=null ? delp : "\t"; // property delimeter
    delo = delo!=null ? delo : "\n"; // object delimeter
    ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
    var str='';

    for(var prop in obj){
        if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
          var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
          str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
        }else{
          str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
        }
    }
    return str;
};

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

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

将显示:

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

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

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

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

使用此项:

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