Javascript javascript检查值是否与对象匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4510234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:42:46  来源:igfitidea点击:

javascript check to see if value matches object

javascriptobject

提问by Mark

I have a javascript object

我有一个 javascript 对象

var obj = {
    "0" : "apple",
    "1" : "pear",
    "2" : "orange"
}

I want to check if 'orange' is in obj.

我想检查 'orange' 是否在 obj 中。

Is there a built in function that does this? Or should I iterate over each value of obj?

有没有内置函数可以做到这一点?或者我应该遍历 obj 的每个值?

Thanks.

谢谢。

回答by Pointy

You'll have to iterate:

你必须迭代:

for (var k in obj) {
  if (!obj.hasOwnProperty(k)) continue;
  if (obj[k] === "orange") {
    /* yaay! an orange! */
  }
}

Now that "hasOwnProperty" test in there is to make sure you don't stumble over properties inherited from the prototype. That mightnot 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.)

现在,“hasOwnProperty”测试是为了确保您不会偶然发现从原型继承的属性。在某些情况下这可能是不可取的,实际上这是您需要了解的事情之一,以便确定您是否想要或不想进行该测试。您从对象的原型中获取的属性有时可能是由各种库放置在那里的东西。(我认为 ES5 标准提供了控制这些属性是否“可迭代”的方法,但在现实世界中仍然存在 IE7。)

回答by Coin_op

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.

同样从您的对象的外观来看,它应该是一个数组而不是一个对象。如果是这种情况,迭代这些值会稍微容易一些,并且效率会稍微提高一些。

var arr = ['apple','pear','orange'];
function inArray(inVal){
    for( var i=0, len=arr.length; i < len; i++){
        if (arr[i] == inVal) return true;
    }
    return false;
}

回答by Herms

function has(obj, value) {
  for(var id in obj) {
    if(obj[id] == value) {
      return true;
    }
  }
  return false;
}

if(has(obj, "orange")) { /* ... */ }

回答by Mark Baijens

You might wanna look at jQuery.inArray. Think it works for objects aswell.

你可能想看看jQuery.inArray。认为它也适用于对象。