Splice use Note When array loops delete data

Source: Internet
Author: User

When deleting an element in the loop array, do not use the splice method.

The problem occurs because splice causes the original array to change, and the array is still in the loop.

Example:

There are a number of groups FormData , requirements: Delete FormData itemlist, Queid = = = ' 001 ' of an item.

The first thing I used was the splice method, but the error was:

 for this. formData.itemList.length; i++) {    this. formdata.itemlist[i]    if (Item.queid = = = ' 001 ') {         this. FormData.itemList.splice (i, 1)     }}

When you encounter a situation where you need to loop an array to delete the array data, do this:

Let Formarr = []for this. formData.itemList.length; i++) {    this. formdata.itemlist[i]    if (Item.queid!== ' 001 ') {        Formarr. Push ({... item})}     }
The last Formarr is to erase the array of data.

Explain Formarr.push ({... item})
Here is the {... item} meaning to copy the item to Formarr, because then Formarr may have an action on item, and if it is directly push item, it will be the same as the reference address of the previous item, which may cause problems. Well.
Note that this copy is only one level of item. If you have more than one layer, you need to use Clonedeep

Splice use Note When array loops delete data

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.