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

标签 javascript jquery backbone.js

抱歉,如果这是多余的,但我已经在这里搜索了几个问答,但我仍然无法弄清楚我做错了什么。我有一个保存为 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);

},

这是我的 Backbone 收藏:

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

关于Javascript/Backbone - 使用索引删除数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090593/

相关文章:

javascript - 显示符合特定条件的帖子总数

javascript - 在 Chrome 中为图像使用 "prefetch"链接

javascript - "ESLint no-loop-func rule"回调中需要循环变量怎么办

javascript - 从html中获取类名的正则表达式

jQuery 触发器在 Safari 中不起作用

javascript - backbone.js 中的时间间隔

javascript - 在 Meteor 发布功能中获取用户的电子邮件地址

JavaScript split() 方法导致未定义

javascript - 从 Node JavaScript 返回到 jQuery 的 Ajax 调用出现错误函数

javascript - 检查主干js中的某个东西是否是模型或集合