Javascript 如何获取对象中键值对的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11279093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a listing of key value pairs in an object?
提问by Leila Hamon
Possible Duplicate:
best way to get the key of a key/value javascript object
foo = {bar: "baz"}
foo = {bar: "baz"}
How do you get a listing of all the properties and values within foo?
如何获得 foo 中所有属性和值的列表?
回答by sachleen
A for in
loop can give you the key and value.
一个for in
循环可以给你的键和值。
for(p in foo) {
console.log (p, foo[p])
}
From the console:
从控制台:
foo = {bar: "baz"}
Object
bar: "baz"
__proto__: Object
for(p in foo) { console.log (p, foo[p]) }
> bar baz
If the object you're looping over has has inherited properties from its prototype, you can prevent the inherited properties from being looped over using the Object.hasOwnProperty()
function like this:
如果您循环的对象从其原型继承了属性,您可以使用如下Object.hasOwnProperty()
函数防止继承的属性被循环:
for(p in foo) {
if (foo.hasOwnProperty(p)) {
console.log (p, foo[p])
}
}
回答by Joseph Marikle
回答by dtx
This can be different for the different platforms that you are currently working on. If you are running from terminal then you use print
, if you dont have the console
object then you can use document.write()
and so on.
对于您当前使用的不同平台,这可能会有所不同。如果您从终端运行,则使用print
,如果您没有console
对象,则可以使用document.write()
等等。
Here is something that you can use/read to understand:
以下是您可以使用/阅读以了解的内容:
var foo = {bar: "baz", boolean: true, num: 2}
for (i in foo) {
//checks to see where to print.
if (typeof console === 'object')
console.log(i + ": " + foo[i]);
else if (typeof document === 'object')
document.write(i + ": " + foo[i]);
else
print(i + ": " + foo[i]);
}
Alternatively, if you just say console.log(foo)
in Chrome/Firefox, the browsers do the looping-highlighting for you and give you a pretty-print of your object, so you dont really need to do the looping shown above.
或者,如果您只是console.log(foo)
在 Chrome/Firefox 中说,浏览器会为您执行循环突出显示并为您提供对象的漂亮打印,因此您实际上不需要执行上面显示的循环。
You can also use console.debug(foo)
instead of console.log(foo)
, the difference is subtle. You can read more about this at http://getfirebug.com/wiki/index.php/Console_API
您也可以使用console.debug(foo)
代替console.log(foo)
,区别很微妙。您可以在http://getfirebug.com/wiki/index.php/Console_API阅读更多相关信息