javascript |在对象中搜索

时间:2014-10-03 10:43:41

标签: javascript object key key-value

我有一个对象:

var obj = {7:[57,58], 8:[37]}

如果对象中存在键/值,我正在寻找返回true或false的函数。

例如:

function check(key, value) { //  7,58

   return true;
}

我该怎么做?谢谢!

3 个答案:

答案 0 :(得分:2)

你可以这样做:

var obj = {7:[57,58], 8:[37]}

function check(key, val) {
    return !!obj[key]&&!!~obj[key].indexOf(val);
}

check(7, 58); // true
check(7, 57); // true
check(8, 9); // false

答案 1 :(得分:1)

function check(obj, key, value) {
    return (obj[key]) ? (obj[key].indexOf(value) != -1) : false;
}

答案 2 :(得分:1)

使用some

function check (key, value) {

  //  Grab the object keys and iterate over them using `some`
  return Object.keys(obj).some(function (el) {

      // make sure you convert `el` to an integer before checking
      // it against the key
      return parseInt(el, 10) === key && obj[el].indexOf(value) > -1;
   });
}

DEMO