如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
这是函数。
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)))};
它可以使用具有可读性的制表符缩进来显示对象。
其他回答
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。
我需要一种递归打印对象的方法,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) );
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
其中object是您的对象
或者您可以在chrome开发工具的“控制台”选项卡中使用此选项:
console.log(对象);
在NodeJS中,您可以使用util.inspect(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/