国外网站上 js 遍历 object 属性和值的方法
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; };
</pre><pre code_snippet_id="515740" snippet_file_name="blog_20141111_2_4562501" name="code" class="html">20:48:20 烟飞烟散 2014/11/11 20:48:20 function printAllObject( 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 = ''; } var levelStr = ''; for ( var x = 0; x < level; x++ ) { levelStr += ' '; } if ( maxLevel != 0 && level >= maxLevel ) { str += levelStr + '...'; return str; } for ( var p in o ) { if ( typeof o[p] == 'string' ) { str += levelStr + p + ':' + o[p] + ''; } else { str += levelStr + p + ': { ' + printAllObject( o[p], maxLevel, level + 1 ) + levelStr + '}'; } } // 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 += ''; } return str; };
<pre name="code" class="javascript">function printAllObject( 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 = ''; } var levelStr = ''; for ( var x = 0; x < level; x++ ) { levelStr += ' '; } if ( maxLevel != 0 && level >= maxLevel ) { str += levelStr + '\n'; return str; } for ( var p in o ) { if ( typeof o[p] == 'string' ) { str += levelStr + p + ': ' + o[p] + ' \n'; } else { str += levelStr + p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}\n'; } } // 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 += ''; } return str; }
来自:http://stackoverflow.com/questions/957537/how-can-i-print-a-javascript-object