Shan  Luo
Shan Luo

Reputation: 63

Why does .splice always delete the last element?

In the javascript, there are two arrays:tags[] and tags_java[]. I use .splice to delete certain items, which of the same index in the two arrays. The tags[] works fine, but tags_java doesn't, it seems always delete the last item.
Here is the code and the jsfiddle link.

var tag = $(this).text();
var index = $.inArray(tag, tags);
    tags.splice(index,1);
    tags_java.splice(index,1); 

Upvotes: 1

Views: 6439

Answers (2)

JimmiTh
JimmiTh

Reputation: 7449

Nah, both don't work, because you're not actually finding the correct index of your tag.

Why not? Because $(this).text() includes the delete mark you added, × - e.g. "Morning×". Since that's not in your tags array, index will be -1. tags.splice(-1, 1); will remove 1 item from the end of the array.

In general, it's never a good idea to use presentation text (i.e. the text of your tag element) as data (e.g. using that text as a lookup value in an array). It's very likely that it'll be broken when something changes in the presentation - like here. So a suggestion would be to store the data (what you need to look up the tags) as data - e.g. using the jQuery-provided data() API - even if it seems redundant.

Here's a quick example - just adding/replacing two lines, which I've marked with comments starting with "JT": JSFiddle

Now, instead of looking up by $(this).text(), we're looking up by the data value "tagValue" stored with $(this).data() - that way, the lookup value is still bound to the element, but we're not relying on presentation text.

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 220026

If the tag is not in the tags array, $.inArray will return -1, which would then cause the last item to be deleted.

You have to make sure that the item is actually in the array.

Upvotes: 1

Related Questions