Javascript/Backbone-使用索引删除数组对象

Javascript/Backbone - Delete Array Object Using Index

本文关键字:删除 数组 对象 索引 Backbone- Javascript      更新时间:2023-09-26

如果这是多余的,很抱歉,但我已经搜索了几个问答;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);
},

这是我的主干收藏:

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

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参数。