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

与显示对象的格式相同。


当前回答

Javascript函数

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

正在打印对象

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

通过Javascript中的print_r

其他回答

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

最简单的答案

我很惊讶,这没有一个更简单的答案,只是一群人重复着完全相同的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

我需要一种递归打印对象的方法,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) ); 

Javascript函数

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

正在打印对象

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

通过Javascript中的print_r

使用本机JSON.stringify方法。适用于嵌套对象,所有主要浏览器都支持此方法。

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参考和其他示例。

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

如果您遇到此Javascript错误

"Uncaught TypeError: Converting circular structure to JSON"