通常如果我们只使用alert(object);它将显示为[object object]。如何在JavaScript中打印对象的所有内容参数?
当前回答
你可以使用Node的util.inspect(object)来打印出对象的结构。
当你的对象有循环依赖时,这是特别有用的。
$ node
var obj = {
"name" : "John",
"surname" : "Doe"
}
obj.self_ref = obj;
util = require("util");
var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: 'John', surname: 'Doe', self_ref: [Circular] }
它是JSON。stringify抛出异常:TypeError:转换循环结构为JSON
其他回答
如果你只是想要一个对象的字符串表示,你可以使用JSON。stringify函数,使用JSON库。
您应该考虑使用FireBug进行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);
你可以在你的对象原型中给他们自己的toString方法。
使用JSON.stringify,这将为您提供一个缩进的JSON对象的非常好的输出:
alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));
第二个参数(replacer)在返回字符串之前改变字符串的内容。
第三个参数(space)指定使用多少个空格作为可读性空白。
JSON。在这里Stringify文档。