本文介绍了获取键/值javascript对象的键的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个JS对象:
If I have a JS object like:
var foo = { 'bar' : 'baz' }
如果我知道 foo
具有该基本键/值结构,但不知道密钥的名称,最简单的方法是什么? for ... in
? $。每个()
?我希望有更好的东西....
If I know that foo
has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it? for ... in
? $.each()
? I hope there's something better....
推荐答案
如果你想得到所有的钥匙,。这仅适用于较新的浏览器,但提供了替代实现(在 btw中也使用):
If you want to get all keys, ECMAScript 5 introduced Object.keys
. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in
btw):
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
当然,如果你想要,密钥和价值,那么 for ... in
是唯一合理的解决方案。
Of course if you want both, key and value, then for...in
is the only reasonable solution.
这篇关于获取键/值javascript对象的键的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!