【问题标题】:How to remove item from array object in jquery如何从jQuery中的数组对象中删除项目
【发布时间】:2012-03-10 19:23:20
【问题描述】:

如何从 jquery 数组对象中删除项目。

我使用拼接方法如下。但它切片数组[i]的下一项。

    $.each(array, function (i, item) {
    var user = array[i];
    jQuery.each(array2, function (index, idata) {
        debugger
        if (idata.Id == user.UserId) {
            tempFlag = 1;
            return false; // this stops the each
        }
        else {
            tempFlag = 0;
        }
    });

    if (tempFlag != 1) {
     //removes an item here

        array.splice(user, 1);
    }
})

谁能告诉我这里哪里错了?

【问题讨论】:

    标签: jquery arrays object splice


    【解决方案1】:

    你应该尝试这个从 jQuery 中的数组中删除元素:

    jQuery.removeFromArray = function(value, arr) {
        return jQuery.grep(arr, function(elem, index) {
            return elem !== value;
        });
    };
    
    var a = [4, 8, 2, 3];
    
    a = jQuery.removeFromArray(8, a);
    

    查看此链接了解更多信息:Clean way to remove element from javascript array (with jQuery, coffeescript)

    【讨论】:

    • 这很干净,但不适用于当前形式的问题,因为代码不仅在数组中查找项目,还在查找另一个数组中包含的项目的数组中的项目一个属性对应于项目的一个属性。
    【解决方案2】:

    您使用user 中的值作为索引,即array[i],而不是值i

    $.each(array, function (i, item) {
      var user = array[i];
      jQuery.each(array2, function (index, idata) {
        debugger
        if (idata.Id == user.UserId) {
          tempFlag = 1;
          return false; // this stops the each
        } else {
          tempFlag = 0;
        }
      });
    
      if (tempFlag != 1) {
        //removes an item here
        array.splice(i, 1);
      }
    });
    

    您可能会在从当前循环的数组中删除项目时遇到问题...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多