通常如果我们只使用alert(object);它将显示为[object object]。如何在JavaScript中打印对象的所有内容参数?
当前回答
所有Javascript !
String.prototype.repeat = function(num) {
if (num < 0) {
return '';
} else {
return new Array(num + 1).join(this);
}
};
function is_defined(x) {
return typeof x !== 'undefined';
}
function is_object(x) {
return Object.prototype.toString.call(x) === "[object Object]";
}
function is_array(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
/**
* Main.
*/
function xlog(v, label) {
var tab = 0;
var rt = function() {
return ' '.repeat(tab);
};
// Log Fn
var lg = function(x) {
// Limit
if (tab > 10) return '[...]';
var r = '';
if (!is_defined(x)) {
r = '[VAR: UNDEFINED]';
} else if (x === '') {
r = '[VAR: EMPTY STRING]';
} else if (is_array(x)) {
r = '[\n';
tab++;
for (var k in x) {
r += rt() + k + ' : ' + lg(x[k]) + ',\n';
}
tab--;
r += rt() + ']';
} else if (is_object(x)) {
r = '{\n';
tab++;
for (var k in x) {
r += rt() + k + ' : ' + lg(x[k]) + ',\n';
}
tab--;
r += rt() + '}';
} else {
r = x;
}
return r;
};
// Space
document.write('\n\n');
// Log
document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};
// Demo //
var o = {
'aaa' : 123,
'bbb' : 'zzzz',
'o' : {
'obj1' : 'val1',
'obj2' : 'val2',
'obj3' : [1, 3, 5, 6],
'obj4' : {
'a' : 'aaaa',
'b' : null
}
},
'a' : [ 'asd', 123, false, true ],
'func' : function() {
alert('test');
},
'fff' : false,
't' : true,
'nnn' : null
};
xlog(o, 'Object'); // With label
xlog(o); // Without label
xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');
var no_definido;
xlog(no_definido, 'Undefined!');
xlog(true);
xlog('', 'Empty String');
其他回答
如果您使用的是Firefox, alert(object.toSource())应该足以满足简单的调试目的。
如果你只是想要一个对象的字符串表示,你可以使用JSON。stringify函数,使用JSON库。
你也可以使用Prototype的object .inspect()方法,该方法“返回对象的面向调试的字符串表示”。
http://api.prototypejs.org/language/Object/inspect/
ie8有开发工具,类似于Firefox的Firebug。Opera有Opera DragonFly,谷歌Chrome也有开发人员工具(Shift+Ctrl+J)。
下面是在IE6-8中调试JavaScript的更详细的答案: 使用IE8“开发人员工具”调试早期IE版本
除了使用调试器,还可以使用foreach循环访问对象的所有元素。下面的printObject函数应该alert()您的对象,显示所有属性和各自的值。
function printObject(o) {
var out = '';
for (var p in o) {
out += p + ': ' + o[p] + '\n';
}
alert(out);
}
// now test it:
var myObject = {'something': 1, 'other thing': 2};
printObject(myObject);
使用DOM检查工具更可取,因为它允许您挖掘对象本身的属性。Firefox有FireBug,但所有其他主要浏览器(IE、Chrome、Safari)也有内置的调试工具,你应该检查一下。