【问题标题】:Filter items in JavaScript Array using jQuery使用 jQuery 过滤 JavaScript 数组中的项目
【发布时间】:2010-01-18 09:34:50
【问题描述】:

我有一个如下的 JavaScript 数组,我需要对其进行过滤以从下面的测试数据中获取正确的子值。

var arrChildOptions2 = [
        {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
        {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'},
        {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'}
    ];

这些值用于根据父下拉列表的更改事件填充下拉列表,如下所示。

$(function() {
    $('#ddl1').change(function() {
        $('#ddl2 option:gt(0)').remove();
        $('#ddl2').addItems('#ddl2', arrChildOptions2[Parent=opt2]);
    });
});

其中 additems 是一个遍历数组的函数。问题是我不能让它按父母过滤,我试过使用 contains 和上面的 arrChildOptions2[Parent=opt2] 但我不能让它过滤器,我更愿意找到一个简洁的解决方案而不是使用 for 循环?任何想法,干杯

【问题讨论】:

标签: javascript jquery


【解决方案1】:

使用jQuery.grep() 函数而不是搞乱循环可能会更幸运。

此函数“查找满足过滤功能的数组元素。原始数组不受影响”。

【讨论】:

  • 优秀的菲尔,谢谢你,我不知道这个功能,对 jquery 来说还是很新,很好用。
【解决方案2】:

array.filter() 存在于原生 JavaScript 中:

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

该文档页面包含适用于旧版浏览器的 polyfill:

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

【讨论】:

    【解决方案3】:

    是的,试试 jquery grep,像这样:

    arr = jQuery.grep( JSON_ARRAY, index);
    

    【讨论】:

      猜你喜欢
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 2011-09-14
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多