开发者

javascript check to see if value matches object

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.


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 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.

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;
}


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜