如何在Chrome控制台中显示完整对象

170
var functor=function(){
    //test
}

functor.prop=1;

console.log(functor);

这只展示了函数部分的函数对象,在控制台中无法展示函数对象的属性。

9个回答

272

1
需要注意的是,在Chrome控制台中只需打印“varName”并按Enter键,就可以达到与“console.dir(varName)”相同的效果。 - Vadzim
@Vadzim 我不认为这还是正确的。例如,尝试使用您选择的HTML元素进行测试。 - Niels Bom

126

如果您尝试以下方法,则可能会获得更好的结果:

console.log(JSON.stringify(functor));

这个答案很好,但我认为它不能与上面的示例一起使用,在新标签页中尝试返回未定义。 - aitorllj93
3
尊重这个答案,但最终它返回的是代表对象的字符串,而不是控制台中可浏览的对象,正如问题所关注的一样。当然,如果你通过JSON.parse运行这个输出字符串,它会返回到对象格式,但控制台仍然会显示它作为".toString()",我们又回到了原点。在这里使用"console.dir"的答案最适合这个问题。 - TheCuBeMan

38

如果你尝试以下方法,可能会获得更好的结果:

console.log(JSON.stringify(obj, null, 4));

这个答案在 @BastiBen 的基础上改进了输出格式。 - Xeoncross

14
var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));

9
这对我非常有效:
for(a in array)console.log(array[a])

您可以提取在控制台创建的任何数组,以进行查找/替换清理并后续使用已提取的数据。

3
稍微详细一些:for (i in arr) { console.log(i); console.log(arr[i]); }这段代码使用 JavaScript 编写,它使用 for 循环语句遍历一个数组中的所有元素。对于数组 arr 中的每个元素,该循环将会输出两行信息。第一行包含该元素在数组中的索引 i,第二行则包含该元素的值 arr[i]。通过这种方式,程序员可以轻松访问和处理数组中的所有元素。 - Geo
它不会输出不可枚举的属性和方法。 - stackoverflow

5
我制作了一个Trident D'Gao答案函数。
function print(obj) {
  console.log(JSON.stringify(obj, null, 4));
}

如何使用它

print(obj);

0
另一种方法是将函数包装成一个数组:
console.log( [functor] );

0

在现代浏览器中,console.log(functor)可以完美地工作(与console.dir的行为相同)。


0
我编写了一个函数,方便地将内容打印到控制台。
// function for debugging stuff
function print(...x) {
    console.log(JSON.stringify(x,null,4));
}

// how to call it
let obj = { a: 1, b: [2,3] };
print('hello',123,obj);

将在控制台中输出:

[
    "hello",
    123,
    {
        "a": 1,
        "b": [
            2,
            3
        ]
    }
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接