繁体   English   中英

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

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

单击图像时,我的代码应该将图像_id详细信息添加到clickedImagesArray数组中。 这确实成功。 但是,当再次单击该图像时,我的代码无法将其从clickedImagesArray数组中删除。

在我的代码下面找到:

"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});

我有一种感觉,我没有正确使用splice()函数。

        }     
  }); 

});

任何帮助将不胜感激。

您需要在包含您的值的数组中提取索引。 然后使用splice从索引中删除该记录。

splice(startIndex, deleteCount)

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);
}

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

我认为这里有一个错误:

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

您应该更改为:

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

这是因为您不知道元素的确切索引。

哦,拼接也是错误的,您需要找到元素的索引以将其删除,如下所示:

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

暂无
暂无

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

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