2013-08-06 52 views
1

對不起,如果這是多餘的,但我已經通過幾個Q & A在這裏搜索,但我仍然無法弄清楚我做錯了什麼。我有保存爲骨幹集合的數組,我需要使用它的索引從數組中刪除的對象:Javascript/Backbone - 使用索引刪除數組對象

deleteCartItem: function(e) { 
    var itemIndex = $(e.currentTarget).attr("data-index"); 
    console.log(itemIndex) 
    console.log(this.collection) 
    console.log(this.collection.length) 
    var newCollection = this.collection.splice(itemIndex); 
    console.log(newCollection.length); 

}, 

這裏是我的骨幹收集:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object] 

回答

2

splice實際修改集合,並返回刪除的項目。請參閱該文檔在這裏:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

試試這個:

deleteCartItem: function(e) { 
    var itemIndex = $(e.currentTarget).attr("data-index"); 
    console.log(itemIndex) 
    console.log(this.collection) 
    console.log(this.collection.length) 
    this.collection.splice(itemIndex, 1); 
    console.log(this.collection.length); 

}, 

還要注意howMany參數。