如果我们有一个javascript对象

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


找到(含)280卡路里水果的最佳方法是什么?

可以Object.getOwnPropertyNames(calories).forEach...,但应该有更好的方法。

例如,我在考虑Array.prototype.indexOf()对数组执行相同的操作。

最佳答案

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

var fruit = null;

for (var prop in calories) {

  if (calories[prop] == 280) {

    fruit = prop;
    break;
  }
}

10-08 17:38