简体   繁体   English

使用Splice()函数,如何删除特定的数组元素?

[英]Using Splice() function, how do I remove specific array elements?

When an image is clicked, my code is supposed to adds the images _id details to the clickedImagesArray array. 单击图像时,我的代码应该将图像_id详细信息添加到clickedImagesArray数组中。 This it does successfully. 这确实成功。 However when the image is clicked again, my code fails to remove it from the clickedImagesArray array. 但是,当再次单击该图像时,我的代码无法将其从clickedImagesArray数组中删除。

Find below my code: 在我的代码下面找到:

"click .image": function (event) {

var clickedImage = [this._id];
var clicked = this._id;
var clickedImagesArray = Session.get('clickedImages');

clickedImage.forEach(function (clicked){
    //#### If no duplcate then push() 
    if (clickedImage.indexOf(clicked) ==-1) {
        alert("NOOOO Duplicates!" + clicked);  
        clickedImagesArray.push({imageId: clicked});
        }
    else if (clickedImage.indexOf(clicked) == 0) {
    //#### Else when duplcate found delete duplicate
        alert("Found Duplicates!" + clicked);       
        clickedImagesArray.splice({imageId: clicked});

I have a feeling I am not using the splice() function correctly. 我有一种感觉,我没有正确使用splice()函数。

        }     
  }); 

});

Any help would be greatly appreciated. 任何帮助将不胜感激。

You need to extract the index in the array that contains your value. 您需要在包含您的值的数组中提取索引。 and then use splice to remove that record from the index. 然后使用splice从索引中删除该记录。

splice(startIndex, deleteCount)

startIndex: is the index that you want to start deleting from deleteCount: the number of records that you want to delete, starting from the startIndex startIndex:是要开始从deleteIndex删除的索引Count:要删除的记录数,从startIndex开始

// find the index of the imageId in the array.
var index = clickedImage.indexOf(clicked);

// if item is found in the array remove it.
if (index !== -1) {
  // remove one item starting from the index.
  clickedImage.splice(index, 1);
}

read the documentation in MDN. 阅读MDN中的文档。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

I think that there is a mistake here: 我认为这里有一个错误:

else if (clickedImage.indexOf(clicked) == 0) {

You should change to: 您应该更改为:

else if (clickedImage.indexOf(clicked) != -1) {

This is because you don´t know the exact index of your element. 这是因为您不知道元素的确切索引。

Oh, and the splice is wrong too, you need to find the index of the element to remove it, like this: 哦,拼接也是错误的,您需要找到元素的索引以将其删除,如下所示:

clickedImagesArray.splice(clickedImage.indexOf(clicked), 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM