【问题标题】:Searching for objects in JavaScript arrays在 JavaScript 数组中搜索对象
【发布时间】:2011-04-07 04:29:47
【问题描述】:

如何在不使用 JavaScript 中的 for 循环的情况下搜索数组中对象的属性?

如果数组是一个简单的数组,我可以使用array.indexOf(value) 来获取索引,但是如果数组是对象数组呢?除了循环还有其他方式吗?

例如,ar = [{x,y},{p,q},{u,v}]。如果搜索v,它应该返回数组索引为2。

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    在数组中搜索值通常需要sequential search,这需要您遍历每个项目,直到找到匹配项。

    function search(ar, value) {
      var i, j;
      for (i = 0; i < ar.length; i++) {
        for (j in ar[i]) {  
          if (ar[i][j] === value) return i;
        }
      }
    }
    
    search([{'x': 'y'}, {'p': 'q'}, {'u': 'v'}], 'v'); // returns 2;
    

    【讨论】:

    • 是的,这样我就明白了。我想如果有一些内置函数来进行搜索,比如我们可以使用 array.sort() 和比较函数根据 objects 属性对数组进行排序。
    • @sat:不是真的。这些是可用于数组的方法:developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…。在 JavaScript 1.6 中有 filter() 方法,但这对于您的要求来说仍然过于复杂。
    【解决方案2】:

    Searching for objects in JavaScript arrays

    javascript:
       /* quick fix naive short solution to be posted soon */
       /* array of objects with primitive property values only and no wrinkles */
    

    .

    javascript:
       alert(
          JSON.stringify(
             [{x:1,y:2},,,{p:"q"},{u:{},vx:[],x:{y:{},x:5}}]
                 ) . match(/"x":/g)
        )
    

    javascript:   /*  Does the need to fortify this code imply JSON is stronger?  */
       alert(                                             /*  See wrinkles below  */
          [{x:1,y:2},,,{p:"q"},{u:{},vx:[],x:{y:{},x:5}}] . toSource() .
     /*
             match(/({|,)\s*x:/g) . join() . replace(/({|,)\s*x:/g,"x:")
       finds `x:,x:,x:`
     */
             replace(/(({|,)\s*)([^,{:]*):/g,'$1"$3":') . match(/"x":/g)
        )
    

    找到"x":,"x":,"x":

    找到特定的财产,完成交易?

    提示,提示(但对于嵌套的动物,必须适当减弱和截肢):

    javascript:
        alert(
            JSON.stringify([{x:1,y:2},{p:"q"},{u:{},v:[],x:{y:{},x:5}}]) . 
                 match(/"[^"]*":/g)
        )
    

    找到"x":,"y":,"p":,"u":,"v":,"x":,"y":,"x":(所有属性 - 现在完成了吗?)

    更多(更多)大脑劳损疼痛将找到x:values 和数组位置索引(提示计数顶级,'s)。

    截断和衰减提示(仅删除嵌套数组和对象,,见皱纹):

    javascript:debug=false;
       animal=[
          {x:1,y:2},,,{p:"q"},
             [ {u:{},vx:[,,], x:{y:{xx:''},x:5} }, "hmmm comma x colon \" monster" ],
       ];
       animal=animal.toSource().replace(/\[(.*)]/,"$1");
    /*  */ if(debug){
       alert(animal);
       animal=animal.replace(/\[([^[\]]*)\]/g,
                   function(a,b,c,d){alert([a,b,c,d].join("\n\n"));return a});
       while(animal.search(/\{.*\}|\[.*\]/)>-1){
          animal=animal.replace(/\{([^{}]*)\}|\[(.*)\]/g,
             function(a,b,c,d){alert([a,"\n",b,"\n",c]);return b.replace(/,/g,";")});
          alert(animal); }
    /*  */   }
    
      /* the while loops on nesting depth not top array length */
       while(animal.search(/\{.*\}|\[.*\]/)>-1)
          animal=animal.replace(/\{([^{}]*)\}|\[(.*)\]/g,       /* implicit g loop */
                      function(a,b,c,d){return (b+c).replace(/,/g," ")}); /* ditto */
       alert(animal);    /* as opposed to a non-lert animal? */
    

    皱纹:

    • .toSource()JSON 更强大(但...见上文)并处理更多情况@
      参考:Implementing Mozilla's toSource() method in Internet Explorer

    • 如果怪物的字符串包含:
      1. , 的。 . .如 . . . [",,or",,{p:"1,2,3,"}]
      2. {x:...}{"x":...} 。 . .如 . . . ['{"x":...}'," and ","{x:...}",,]
        (这将使用JSONtoSource 搞砸上述编码)
      3. 嵌套怪物
      4. 其他怪物只是幻想......没有足够的报酬去做或证明

    【讨论】:

      猜你喜欢
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2017-07-22
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多