gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:55:39 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com