用 map() 迭代并删除没有索引的拼接对象

Iterate with map() and delete object with splice without index

我可以删除带有拼接的元素,但在地图中 cicle 索引是已知的。

if ($(this).hasClass("saveFavoriteMedia")) {
                    saveId = $(this).attr("data-id");
                    listFavoriteMedia.map(function (x) {
                        if (x.id == saveId) {
                            //delete x.id; // Work but not delete totaly elements
                            listFavoriteMedia.splice(index, x.id); //index in already know
                        }
                    });
                }

您可以使用 map 的回调函数的第二个参数 - index

listFavoriteMedia.map(function (x,i) { //i is the index
    if (x.id == saveId) {
       listFavoriteMedia.splice(i, 1);  //observe that 1 is given as second parameter of splice to give count of items to be deleted
    }
});

或者如果 id 是唯一的,则使用 findIndex

var index = listFavoriteMedia.findIndex( s => s.id == saveId );
listFavoriteMedia.splice(index, 1); 

如果您的浏览器不支持箭头功能,那么

var index = listFavoriteMedia.findIndex( function(s){ return s.id == saveId });
listFavoriteMedia.splice(index, 1); 

您可以为此使用过滤器;

 listFavoriteMedia = listFavoriteMedia.filter(function(x){
      if (x.id !== saveId) {
        return true;
      }
    });