在JavaScript对象,什么是得到一个值的属性最好的方法? [英] in a javascript object, what's best way to get the attribute of a value?
本文介绍了在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;
}
}
这篇关于在JavaScript对象,什么是得到一个值的属性最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文