通常如果我们只使用alert(object);它将显示为[object object]。如何在JavaScript中打印对象的所有内容参数?
当前回答
简单的函数提醒对象或数组的内容。 用数组或字符串或对象调用此函数,它会提醒内容。
函数
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
使用
var data = [1, 2, 3, 4];
print_r(data);
其他回答
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)也有内置的调试工具,你应该检查一下。
你可以在你的对象原型中给他们自己的toString方法。
使用JSON.stringify,这将为您提供一个缩进的JSON对象的非常好的输出:
alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));
第二个参数(replacer)在返回字符串之前改变字符串的内容。
第三个参数(space)指定使用多少个空格作为可读性空白。
JSON。在这里Stringify文档。
您应该考虑使用FireBug进行JavaScript调试。它将允许您交互式地检查所有变量,甚至逐步通过函数。