【问题标题】:javascript | search in objectjavascript |在对象中搜索
【发布时间】:2014-11-28 10:16:05
【问题描述】:

我有一个对象:

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

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

例如:

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

   return true;
}

我该怎么做?谢谢!

【问题讨论】:

    标签: javascript object key key-value


    【解决方案1】:

    你可以这样做:

    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
    

    【讨论】:

      【解决方案2】:
      function check(obj, key, value) {
          return (obj[key]) ? (obj[key].indexOf(value) != -1) : false;
      }
      

      【讨论】:

        【解决方案3】:

        使用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

        【讨论】:

          猜你喜欢
          • 2011-04-07
          • 2020-04-01
          • 1970-01-01
          • 2018-01-05
          • 2019-02-12
          • 2018-02-18
          • 2013-04-02
          • 2011-10-02
          • 1970-01-01
          相关资源
          最近更新 更多