简体   繁体   中英

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); 

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, × - eg "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 (ie the text of your tag element) as data (eg 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 - eg 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM