[JS] Application Splice The pit that occurs when multiple elements are removed

Source: Internet
Author: User

-------------------------------------------------------------------------------------

Let's look at one fragment:

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice (2,2);  # Banana,orange

The above two lines of code are absolutely no problem and can achieve the effect we want.

If it turns out to be the case:

var origin=["AA", "BB", "CC", "DD"]; var has = ["BB", "CC"]; var _index = [];  for inch origin) {    # here or use for: inch , not the    point. if ($.inarray (Origin[i], has)! =-1) {        _index.push (i);    }} # The focus is on for   _index) {    1);} Console.log (origin);  # will now output the results we want ["AA", "DD"]?

Run, we see the result is not what we want, because the original array was changed once splice, the index array index is rearranged neatly, so that the old index of our records is not right.

It turns out that.

So now we need to change the code for the Focus splice section:

var k = 0;  for inch _index) {    -K, 1);    K+ +;}

The principle is that we shrink the index value to achieve the purpose of the index pair to delete the element.

Link:http://www.cnblogs.com/farwish/p/5204370.html

[JS] Application Splice The pit that occurs when multiple elements are removed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.