[英]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.