Javascript:从数组中删除包含带有侦听器的对象的项目的最佳方法

Javascript: Best way to delete item which contains objects with listener from array?

本文关键字:侦听器 对象 项目 方法 最佳 包含带 数组 删除 Javascript      更新时间:2023-09-26

数组中删除包含带有侦听器的对象的项目的最佳方法是什么?我最担心的是对象侦听器。

以下是我创建数组的方法:

array_list.push({data: data, marker: marker, label: label});

数据包含信息,标记是谷歌地图标记,标签是用户可见的div元素。标记和标签添加了侦听器。

我已经找到了几种从数组中清除我的项目的方法(简单的方法):

function remove_item(i) {
  var label = array_list[i]['label'];
  array_list = array_list.filter(function (obj) {
    return obj.label !== label;
  });
}

另一种方式是这样的:

function remove_item(i) {
  var label = array_list[i]['label'];
  array_list = array_list.filter(function (obj) {
    if (obj.label == label) {
      obj.data = null;
      obj.marker = null;
      obj.label = null;
      return null;
    }
    else {
      return obj;
    }
  });
}

拼接方法(也很容易):

function remove_item(i) {
  array_list.splice(i, 1);
}

删除包含侦听器的项目的最佳方法还是有更好的方法?请告诉我。谢谢你的时间。

我最终得到了一个解决方案,其中清除了一个对象并从数组中拼接了该项目。

function remove_item(i) {
  var item = array_list[i];
  // Remove marker from map
  item['marker'].setMap(null);
  // Remove label from html list content
  item['label'].parentElement.removeChild(item['label']);
  // Set Objects to null
  item['data'] = null;
  item['marker'] = null;
  item['label'] = null;
  array_list.splice(i, 1);
}

我希望这也对其他人有所帮助。欢迎提出意见和建议。