javascript 检查值是否与对象匹配
我有一个 javascript 对象
var obj = {
"0" : "apple",
"1" : "pear",
"2" : "orange"
}
,我想检查 obj 中是否有“orange”。
是否有内置函数可以执行此操作?或者我应该迭代 obj 的每个值?
谢谢。
I have a javascript object
var obj = {
"0" : "apple",
"1" : "pear",
"2" : "orange"
}
I want to check if 'orange' is in obj.
Is there a built in function that does this? Or should I iterate over each value of obj?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须迭代:
现在“hasOwnProperty”测试是为了确保您不会绊倒从原型继承的属性。在某些情况下,这可能是不可取的,而且实际上这是您需要了解的事情之一,以便确定您是否愿意进行该测试。您从对象原型中获取的属性有时可能是各种库放置在那里的东西。 (我认为 ES5 标准提供了控制此类属性是否“可迭代”的方法,但在现实世界中仍然存在 IE7。)
You'll have to iterate:
Now that "hasOwnProperty" test in there is to make sure you don't stumble over properties inherited from the prototype. That might not be desirable in some cases, and really it's one of the things you kind-of need to understand in order to know for sure whether you do or don't want to make that test. Properties that you pick up from an object's prototype can sometimes be things dropped there by various libraries. (I think the ES5 standard provides for ways to control whether such properties are "iterable", but in the real world there's still IE7.)
没有内置函数可以执行此操作,您必须检查每个属性。
另外,从对象的外观来看,它应该是一个数组而不是一个对象。如果是这种情况,迭代这些值会稍微容易一些,并且效率会稍微更高。
There is no built in function to do this, you'd have to check each property.
Also by the looks of your object, it should be an array instead of an object. If that was the case it would be slightly easier to iterate through the values and be marginally more efficient.
您可能想查看 jQuery.inArray。认为它也适用于物体。
You might wanna look at jQuery.inArray. Think it works for objects aswell.