如果我有一个JS对象:
var foo = { 'bar' : 'baz' }
如果我知道foo有基本的键/值结构,但不知道键的名称,我怎么能得到它?为…在吗?$ . each () ?
如果我有一个JS对象:
var foo = { 'bar' : 'baz' }
如果我知道foo有基本的键/值结构,但不知道键的名称,我怎么能得到它?为…在吗?$ . each () ?
当前回答
既然你提到了$.each(),下面是一个可以在jQuery 1.6+中工作的方便方法:
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});
其他回答
用于在javascript中访问对象或地图中的键的每个循环
for(key in foo){
console.log(key);//for key name in your case it will be bar
console.log(foo[key]);// for key value in your case it will be baz
}
注:也可以使用
种(foo);
它会像这样给你 输出:
(酒吧);
除了……没有别的办法了。在。如果你不想使用它(可能是因为在每次迭代中测试hasOwnProperty的效率很低?),那么使用一个不同的构造,例如kvp的数组:
[{ key: 'key', value: 'value'}, ...]
既然你提到了$.each(),下面是一个可以在jQuery 1.6+中工作的方便方法:
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});
给你的一句话:
const OBJECT = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
};
const value = 'value2';
const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];
window.console.log(key); // = key2
你可以用for循环在对象内部迭代:
for(var i in foo){
alert(i); // alerts key
alert(foo[i]); //alerts key's value
}
Or
Object.keys(foo)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(foo[key]); // alerts value
});