1

如何从 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);
    }
})

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

4

2 回答 2

6

您应该尝试这样做以从 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);

检查此链接以获取更多信息:从 javascript 数组中删除元素的干净方法(使用 jQuery、coffeescript)

于 2012-02-20T12:55:36.417 回答
4

您正在使用中的值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);
  }
});

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

于 2012-02-20T12:53:57.730 回答