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.

Share Improve this question asked Jan 27, 2013 at 11:30 BernyBerny 1551 silver badge10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

The 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 location
  • item1, item2, item3: Optional items to add at that location (after having deleted, if deleteCount > 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