很抱歉,如果这是多余的,但我在这里搜索了几个Q& A,但我仍然无法弄清楚我做错了什么。我有一个数组保存为主干集合,我需要使用其索引从该数组中删除一个对象:
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);
},
这是我的Backbone Collection:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
答案 0 :(得分: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
参数。