简体   繁体   English

Javascript:从对象中查找值

[英]Javascript: finding a value from an object

I have the following object: 我有以下对象:

var stuff = {}; 
stuff["jar"] = "biscuit"; 
stuff["cupboard"] = "food"; 

Iterating through the list with an For i loop and getting the value is easy, but how would I get the key? 使用For i循环遍历该列表并获取值很容易,但是我将如何获取密钥?

for (var i in stuff) {  
    var key = GET KEY SOMEHOW 
    var val = stuff[i];   
}  

The key is i . 关键是i However, make sure that the key is in your object, not part of the prototype chain. 但是,请确保密钥位于对象中,而不是原型链的一部分。

for (var i in stuff) {
  var key = i;
  if (stuff.hasOwnProperty(i)) {
    var val = stuff[i];   
  }
}  

See also: 也可以看看:

var key = i;

在Javascript的for (foo in bar)如果foo是对象或数组的索引并且恰好是字符串,则在调用foo时应打印或分配该字符串。

You already have it: 您已经拥有它:

for (var key in stuff) {
    var val = stuff[key];
}

If you have the value already you may find the key by using this logic : 如果已经有了值,则可以使用以下逻辑找到键:

for (var i=0;i<numKeyValuePairs;i++)
{
if(val==key[i])
{
document.write(key[i];
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM