在JavaScript对象,什么是得到一个值的属性最好的方法?

问题描述:

如果我们有一个JavaScript对象

if we have a javascript object

var calories = { apple:200, pear:280, banana:300, peach:325 }

什么是找到(第一)的水果,有280卡路里的最佳方式?

what is best way to find the (first) fruit that has 280 calories?

Object.getOwnPropertyNames(卡路里).forEach ... 但应该有一个更好的办法。

could Object.getOwnPropertyNames(calories).forEach... but there should be a better way.

例如,我在想 Array.prototype.indexOf的()由它来完成同样的事情的Array。

For example, I was thinking of Array.prototype.indexOf() which does the same thing for an Array.

使用线性搜索的for..in 结构:

var fruit = null;

for (var prop in calories) {

  if (calories[prop] == 280) {

    fruit = prop;
    break;
  }
}