通常如果我们只使用alert(object);它将显示为[object object]。如何在JavaScript中打印对象的所有内容参数?
当前回答
使用JSON.stringify,这将为您提供一个缩进的JSON对象的非常好的输出:
alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));
第二个参数(replacer)在返回字符串之前改变字符串的内容。
第三个参数(space)指定使用多少个空格作为可读性空白。
JSON。在这里Stringify文档。
其他回答
你可以使用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
你也可以使用Prototype的object .inspect()方法,该方法“返回对象的面向调试的字符串表示”。
http://api.prototypejs.org/language/Object/inspect/
简单的函数提醒对象或数组的内容。 用数组或字符串或对象调用此函数,它会提醒内容。
函数
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);
使用dir(对象)。或者你也可以下载Firebug for Firefox(真的很有用)。
除了使用调试器,还可以使用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)也有内置的调试工具,你应该检查一下。