admin管理员组文章数量:1410723
I want to remove an element from array, but splice method remove all elemts from star index till the end of array.
I have this code:
function basketItemRemove(obj, id) {
...
if (id == 0)
tempBasketList.splice(id, id + 1);
else
tempBasketList.splice(id, id);
...
}
I check id 0, because splice don't remove with index 0. Then splice(id, id);
properly work only with second element of array, but if element is third or higher then it delete all till the end of array.
I want to remove an element from array, but splice method remove all elemts from star index till the end of array.
I have this code:
function basketItemRemove(obj, id) {
...
if (id == 0)
tempBasketList.splice(id, id + 1);
else
tempBasketList.splice(id, id);
...
}
I check id 0, because splice don't remove with index 0. Then splice(id, id);
properly work only with second element of array, but if element is third or higher then it delete all till the end of array.
3 Answers
Reset to default 6The second argument to splice
is how many elements to remove, not the point at which to stop removing them. If you want to remove one element, use 1
:
tempBasketList.splice(id, 1);
I check id 0, because splice don't remove with index 0
It does, but not if that's what you give for the second argument, because it means to remove zero items.
The signature of splice
(from the link above) explained:
splice(start, deleteCount [ , item1 [ , item2 [ , … ] ] ] )
start
: Where to start doing things (the index)deleteCount
: How many to delete at that locationitem1
,item2
,item3
: Optional items to add at that location (after having deleted, ifdeleteCount > 0
)
The syntax of splice
is:
array.splice(index , howMany[, element1[, ...[, elementN]]])
This means that if you need to remove only one single element, the second argument should be 1
:
tempBasketList.splice(id, 1);
I will create a prototype to make thing more easier,
Array.prototype.delete = function (obj) {
var index = this.indexOf(obj);// Get the index of object
this.splice(index, 1);// delete it
};
and then,
tempBasketList.remove(obj)
本文标签: javascript splice don39t work properlyStack Overflow
版权声明:本文标题:javascript splice don't work properly - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744841709a2627962.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论