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

与显示对象的格式相同。


当前回答

功能:

var print = function(o){
    var str='';

    for(var p in o){
        if(typeof o[p] == 'string'){
            str+= p + ': ' + o[p]+'; </br>';
        }else{
            str+= p + ': { </br>' + print(o[p]) + '}';
        }
    }

    return str;
}

用法:

var myObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

$('body').append( print(myObject) );

例子:

http://jsfiddle.net/WilsonPage/6eqMn/

其他回答

如果您正在寻找可以返回任何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"
  }
}

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

在ES2015中,使用对象文本的速记属性声明语法,您可以记录对象,同时也可以简洁地保留变量名:

console.log("bwib:", bwib, "bwab:", bwab, "bwob": bwob) // old way A
console.log({bwib: bwib, bwab: bwab, bwob: bwob})       // old way B

console.log({bwib, bwab, bwob})                         // ES2015+ way

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

这里有一种方法:

console.log("%o", obj);

功能:

var print = function(o){
    var str='';

    for(var p in o){
        if(typeof o[p] == 'string'){
            str+= p + ': ' + o[p]+'; </br>';
        }else{
            str+= p + ': { </br>' + print(o[p]) + '}';
        }
    }

    return str;
}

用法:

var myObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

$('body').append( print(myObject) );

例子:

http://jsfiddle.net/WilsonPage/6eqMn/