首页 文章

如何显示JavaScript对象?

提问于
浏览
1324

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

我希望显示对象的格式相同的方式 .

30 回答

  • 1

    (这已添加到我的图书馆GitHub

    在这里重新发明轮子!这些解决方案都不适用于我的情况 . 所以,我很快就抄写了pagewil的答案 . 这个不是用于打印到屏幕(通过控制台,或文本字段或其他) . 然而,它是用于数据传输的 . 此版本似乎返回与 toSource() 非常相似的结果 . 我没试过 JSON.stringify ,但我认为这是一回事 . 此函数的结果是有效的Javascript对象声明 .

    我不会怀疑这样的事情是否已经出现在某个地方,但它只是缩短了时间而不是花一些时间来搜索过去的答案 . 而且当我开始搜索这个问题时,这个问题是谷歌的热门话题 . 我认为把它放在这里可能会帮助别人 .

    无论如何,此函数的结果将是对象的字符串表示形式,即使您的对象具有嵌入的对象和数组,即使这些对象或数组具有更多嵌入的对象和数组 . (我听说你喜欢喝酒?所以,我用冷却器给你的车拉了个屁 . 然后,我用冷却器给你的冷却器拉了个屁 . 所以,你的冷却器可以喝,而你很酷 . )

    数组与 [] 而不是 {} 一起存储,因此没有键/值对,只有值 . 像常规数组一样 . 因此,它们像数组一样被创建 .

    此外,引用了所有字符串(包括键名),除非这些字符串具有特殊字符(如空格或斜杠),否则不需要这样做 . 但是,我不想检测到这只是为了删除一些原本仍能正常工作的报价 .

    然后,此结果字符串可以与 eval 一起使用,或者只是将其转储到var thru字符串操作中 . 因此,从文本中重新创建对象 .

    function ObjToSource(o){
        if (!o) return 'null';
        var k="",na=typeof(o.length)=="undefined"?1:0,str="";
        for(var p in o){
            if (na) k = "'"+p+ "':";
            if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
            else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
            else str += k + o[p] + ",";
        }
        if (na) return "{"+str.slice(0,-1)+"}";
        else return "["+str.slice(0,-1)+"]";
    }
    

    让我知道如果我搞砸了,我的测试工作正常 . 此外,我能想到检测类型 array 的唯一方法是检查是否存在 length . 因为Javascript确实将数组存储为对象,所以我实际上无法检查类型 array (没有这样的类型!) . 如果其他人知道更好的方式,我很乐意听到它 . 因为,如果您的对象也有一个名为 length 的属性,那么此函数会错误地将其视为数组 .

    编辑:添加了对空值对象的检查 . 谢谢Brock Adams

    编辑:下面是固定功能,可以打印无限递归对象 . 这与FF的 toSource 打印不同,因为 toSource 将打印无限递归一次,此时此函数将立即将其终止 . 这个函数比上面的那个运行得慢,所以我在这里添加它而不是编辑上面的函数,因为如果你计划传递链接回自己的对象,它只需要它 .

    const ObjToSource=(o)=> {
        if (!o) return null;
        let str="",na=0,k,p;
        if (typeof(o) == "object") {
            if (!ObjToSource.check) ObjToSource.check = new Array();
            for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
            ObjToSource.check.push(o);
        }
        k="",na=typeof(o.length)=="undefined"?1:0;
        for(p in o){
            if (na) k = "'"+p+"':";
            if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
            else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
            else str += k+o[p]+",";
        }
        if (typeof(o) == "object") ObjToSource.check.pop();
        if (na) return "{"+str.slice(0,-1)+"}";
        else return "["+str.slice(0,-1)+"]";
    }
    

    测试:

    var test1 = new Object();
    test1.foo = 1;
    test1.bar = 2;
    
    var testobject = new Object();
    testobject.run = 1;
    testobject.fast = null;
    testobject.loop = testobject;
    testobject.dup = test1;
    
    console.log(ObjToSource(testobject));
    console.log(testobject.toSource());
    

    结果:

    {'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
    ({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})
    

    注意:尝试打印 document.body 是一个可怕的例子 . 首先,FF在使用 toSource 时只打印一个空对象字符串 . 使用上述功能时,FF会在 SecurityError: The operation is insecure. 上崩溃 . Chrome将在 Uncaught RangeError: Maximum call stack size exceeded 崩溃 . 显然, document.body 并不意味着转换为字符串 . 因为它要么太大,要么违反安全策略来访问某些属性 . 除非,我搞砸了一些东西,告诉我!

  • 2

    这是功能 .

    function printObj(obj) {
    console.log((function traverse(tab, obj) {
        let str = "";
        if(typeof obj !== 'object') {
            return obj + ',';
        }
        if(Array.isArray(obj)) {            
            return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
        }
        str = str + '{\n';
        for(var p in obj) {
            str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
        }
        str = str.slice(0,-2) + str.slice(-1);                
        str = str + tab + '},';
        return str;
    }('',obj).slice(0,-1)))};
    

    它可以使用带有可读性的制表符缩进来显示对象 .

  • 52

    Function:

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

    Usage:

    var myObject = {
        name: 'Wilson Page',
        contact: {
            email: 'wilson@hotmail.com',
            tel: '123456789'
        }  
    }
    
    $('body').append( print(myObject) );
    

    Example:

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

  • 6

    我总是在我的项目中使用一个小辅助函数,通过控制台进行简单,快速的调试 . 从Laravel采取的灵感 .

    /**
     * @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) + ')');
    }
    

    Usage

    dd(123.55); 输出:

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

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

    希望有所帮助!

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

    其中 object 是你的对象

    或者你可以在chrome dev工具,“console”选项卡中使用它:

    console.log(object);

  • 16

    我需要一种递归打印对象的方法,提供了pagewil的答案(谢谢!) . 我更新了一点,包括一种打印到某个级别的方法,并添加间距,以便根据我们当前的级别正确缩进,以便它更具可读性 .

    // Recursive print of object
    var print = function( o, maxLevel, level ) {
        if ( typeof level == "undefined" ) {
            level = 0;
        }
        if ( typeof level == "undefined" ) {
            maxLevel = 0;
        }
    
        var str = '';
        // Remove this if you don't want the pre tag, but make sure to remove
        // the close pre tag on the bottom as well
        if ( level == 0 ) {
            str = '<pre>';
        }
    
        var levelStr = '';
        for ( var x = 0; x < level; x++ ) {
            levelStr += '    ';
        }
    
        if ( maxLevel != 0 && level >= maxLevel ) {
            str += levelStr + '...</br>';
            return str;
        }
    
        for ( var p in o ) {
            if ( typeof o[p] == 'string' ) {
                str += levelStr +
                    p + ': ' + o[p] + ' </br>';
            } else {
                str += levelStr +
                    p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
            }
        }
    
        // Remove this if you don't want the pre tag, but make sure to remove
        // the open pre tag on the top as well
        if ( level == 0 ) {
            str += '</pre>';
        }
        return str;
    };
    

    用法:

    var pagewilsObject = {
        name: 'Wilson Page',
        contact: {
            email: 'wilson@hotmail.com',
            tel: '123456789'
        }  
    }
    
    // Recursive of whole object
    $('body').append( print(pagewilsObject) ); 
    
    // Recursive of myObject up to 1 level, will only show name 
    // and that there is a contact object
    $('body').append( print(pagewilsObject, 1) );
    
  • 6

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

  • 66

    Javascript Function

    <script type="text/javascript">
        function print_r(theObj){ 
           if(theObj.constructor == Array || theObj.constructor == Object){ 
              document.write("<ul>") 
              for(var p in theObj){ 
                 if(theObj[p].constructor == Array || theObj[p].constructor == Object){ 
                    document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); 
                    document.write("<ul>") 
                    print_r(theObj[p]); 
                    document.write("</ul>") 
                 } else { 
                    document.write("<li>["+p+"] => "+theObj[p]+"</li>"); 
                 } 
              } 
              document.write("</ul>") 
           } 
        } 
    </script>
    

    Printing Object

    <script type="text/javascript">
    print_r(JAVACRIPT_ARRAY_OR_OBJECT);
    </script>
    

    通过print_r in Javascript

  • 17

    使用本机 JSON.stringify 方法 . 适用于嵌套对象和所有主流浏览器support此方法 .

    str = JSON.stringify(obj);
    str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
    console.log(str); // Logs output to dev tools console.
    alert(str); // Displays output using window.alert()
    

    链接到Mozilla API Reference和其他示例 .

    obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
    

    如果遇到此Javascript错误,请使用自定义JSON.stringify replacer

    "Uncaught TypeError: Converting circular structure to JSON"
    
  • 804

    正如之前所说的最好,最简单的方式我找到了

    var getPrintObject=function(object)
    {
        return JSON.stringify(object);
    }
    
  • 2

    如果您希望以表格格式查看数据,则可以使用

    console.table(obj);
    

    如果单击表列,则可以对表进行排序 .

    您还可以选择要显示的列:

    console.table(obj, ['firstName', 'lastName']);
    

    您可以找到有关console.table here的更多信息 .

  • 30

    可能你正在寻找这个

    console.dir()

  • 4

    我认为最好的解决方案是查看对象的键,然后通过Object的值,如果你真的想看看对象的内容......

    console.log(Object.keys(obj));
    console.log(Object.values(obj));
    

    如果您使用ECMAScript 2016或更新版本,还有这个新选项:

    Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));
    
  • 4

    console.dir(object)

    显示指定JavaScript对象属性的交互式列表 . 此列表允许您使用显示三角形来检查子对象的内容 .

    请注意, console.dir() 功能是非标准功能 . 见MDN Web Docs

  • 5

    如果你想打印它的全长物体,可以使用

    console.log(require('util') . inspect(obj,{showHidden:false,depth:null})

    如果要通过将对象转换为字符串来打印对象

    console.log(JSON.stringify(obj));

  • 18

    这是一种方法:

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

    With Firefox

    如果您想打印对象以进行调试,我建议您安装Firebug for Firefox并使用以下代码:

    console.log(obj)
    

    With Chrome

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

    会显示

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

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

    最简单的方法:

    console.log(obj);
    

    或者留言:

    console.log("object is: %O", obj);
    

    传递的第一个对象可以包含一个或多个格式说明符 . 格式说明符由百分号(%)后跟一个表示要应用的格式的字母组成 .

    More format specifiers

  • 3
    var output = '';
    for (var property in object) {
      output += property + ': ' + object[property]+'; ';
    }
    alert(output);
    
  • 31

    试试这个:

    console.log(JSON.stringify(obj))
    

    这将打印对象的stringify版本 . 因此,您将获得对象的内容,而不是 [object] 作为输出 .

  • 1

    使用带有颜色作为奖励的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

  • 372

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

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

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

  • 10

    我总是使用 console.log("object will be: ", obj, obj1) . 这样我就不需要使用带有JSON的stringify来解决这个问题 . 对象的所有属性都将很好地扩展 .

  • 15

    我使用了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;
    };
    
  • 31

    用这个:

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

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

    alert("myObject is " + myObject.toSource());

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

  • 2

    pagewils代码的另一个修改...他不打印除字符串以外的任何内容,并将数字和布尔字段留空,我修复了由megaboss创建的函数内部的第二种类型的拼写错误 .

    var print = function( o, maxLevel, level )
    {
        if ( typeof level == "undefined" )
        {
            level = 0;
        }
        if ( typeof maxlevel == "undefined" )
        {
            maxLevel = 0;
        }
    
        var str = '';
        // Remove this if you don't want the pre tag, but make sure to remove
        // the close pre tag on the bottom as well
        if ( level == 0 )
        {
            str = '<pre>';   // can also be <pre>
        }
    
        var levelStr = '<br>';
        for ( var x = 0; x < level; x++ )
        {
            levelStr += '    ';   // all those spaces only work with <pre>
        }
    
        if ( maxLevel != 0 && level >= maxLevel )
        {
            str += levelStr + '...<br>';
            return str;
        }
    
        for ( var p in o )
        {
            switch(typeof o[p])
            {
              case 'string':
              case 'number':    // .tostring() gets automatically applied
              case 'boolean':   // ditto
                str += levelStr + p + ': ' + o[p] + ' <br>';
                break;
    
              case 'object':    // this is where we become recursive
              default:
                str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
                break;
            }
        }
    
        // Remove this if you don't want the pre tag, but make sure to remove
        // the open pre tag on the top as well
        if ( level == 0 )
        {
            str += '</pre>';   // also can be </pre>
        }
        return str;
    };
    
  • 105

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

    我想这对于大多数调试来说已经足够了 .

相关问题