2017-03-07 84 views
2

我使用的splice函數從陣列和indexOf函數來獲取的元素位置刪除的元素。型 -/JavaScript的 - array.indexOf總是返回-1

但是indexOf返回總是-1,雖然相同的元素是在數組中。

mycode的(Angular2):

subToDelete : Subscription; 
public unsubscribe(topic:string) { 
    this.subToDelete = new Subscription(topic); 
    console.log("DeleteIndex: ",this.subs.indexOf(this.subToDelete)); 
    this.subs.splice(this.subs.indexOf(this.subToDelete),1); 
    console.log("SubTo Delete: ",this.subToDelete); 
    this.subs.forEach(element => { 
    console.log("Subscribed to: ",element); 
    }); 
} 

這是控制檯輸出,在這裏你可以看到,這應該是刪除的元素,包括在陣列中,但indexOf回報-1不過。

http://imgur.com/a/HGz5c(不知何故,我不能上傳照片,所以這裏是鏈接)

+0

由於您的陣列似乎存儲對象和'indexOf'檢查是否嚴格相等,你的'新的訂閱(主題)'永遠不可能等於已經存在的數組元素(因爲你剛剛創建了一個新的對象,它不在數組之前) – UnholySheep

回答

1

你所面臨的問題是因爲你試圖爲一個對象數組中進行搜索。這與一組文字不相同。

你可以做這樣的事情

pos = this.subs.map(function(e) { 
    return e.topic; 
    }) 
    .indexOf(this.subToDelete.topic); 

this.subs.splice(pos,1); 

看看這個question有關該主題的更多信息。

+0

謝謝,它的工作原理:) – ALSTRA

+0

如果主題不存在,indexOf將返回-1,因此splice將從subs中移除最後一個元素。您需要使用if(pos> -1) – rmcsharry

3

您也可以使用這需要萊迭代比map功能Array.prototype.find()

let index: number; 
this.subs.find((item, i) => { if (item.topic === topic) index = i }); 
this.subs.splice(index, 1); 
+0

來保護拼接操作,發現返回的是什麼? – ALSTRA

+0

沒錯。修復了我答案中的代碼 –

0

你也可以使用Array.prototype.findIndex我認爲這是最簡單的解決方案:

let index = this.subs.findIndex((item) => item.topic === topic); 
if (index > -1) this.subs.splice(index, 1);