本文翻译自:Print content of JavaScript object? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- How can I display a JavaScript object? 如何显示JavaScript对象? 37 answers 37个答案
Typically if we just use alert(object);
通常,如果我们只使用alert(object);
it will show as [object Object]
. 它将显示为[object Object]
。 How to print all the content parameters of an object in JavaScript? 如何在JavaScript中打印对象的所有内容参数?
#1楼
参考:https://stackoom.com/question/6on2/打印JavaScript对象的内容-重复
#2楼
You should consider using FireBug for JavaScript debugging. 您应该考虑使用FireBug进行JavaScript调试。 It will let you interactively inspect all of your variables, and even step through functions. 它可以让您交互式地检查所有变量,甚至逐步执行功能。
#3楼
Use dir(object). 使用dir(object)。 Or you can always download Firebug for Firefox (really helpful). 或者,您始终可以下载Firefox的Firebug (非常有用)。
#4楼
You can also use Prototype's Object.inspect() method, which "Returns the debug-oriented string representation of the object". 您还可以使用Prototype的Object.inspect()方法,该方法“返回对象的面向调试的字符串表示形式”。
http://api.prototypejs.org/language/Object/inspect/ http://api.prototypejs.org/language/Object/inspect/
#5楼
如果只想使用对象的字符串表示形式,则可以使用JSON库使用JSON.stringify
函数。
#6楼
Aside from using a debugger, you can also access all elements of an object using a foreach
loop. 除了使用调试器之外,您还可以使用foreach
循环访问对象的所有元素。 The following printObject
function should alert()
your object showing all properties and respective values. 下面的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);
Using a DOM inspection tool is preferable because it allows you to dig under the properties that are objects themselves. 最好使用DOM检查工具,因为它允许您在对象本身的属性下进行挖掘。 Firefox has FireBug but all other major browsers (IE, Chrome, Safari) also have debugging tools built-in that you should check. Firefox具有FireBug,但所有其他主要浏览器(IE,Chrome,Safari)也具有内置的调试工具,您应该检查它们。