当单击图像时,我的代码应该将图像 _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 从索引中删除该记录。
拼接(startIndex,deleteCount)
startIndex:是您要从中开始删除的索引
deleteCount:要删除的记录数,从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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
关于javascript - 使用 Splice() 函数,如何删除特定的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505942/