A brief talk on the precautions for deleting elements in an array using the Splice function _javascript tips

Source: Internet
Author: User

Considerations for deleting elements in an array using the Splice function

Delete an element with a value of C:

<script>
var arr = new Array ();
Arr[0] = ' a ';
Arr[1] = ' B ';
ARR[2] = ' C ';
ARR[3] = ' C ';
ARR[4] = ' e ';

for (var i=0 i<arr.length; i++) {
  if (arr[i] = = ' C ') {
    arr.splice (i,1);
    i=i-1;  I must subtract 1, otherwise one of the following elements will be skipped
  }
</script>

Note: If you use for (i in ARR), one of the following elements will always jump over

<script>

var arr = new Array ();
Arr[0] = ' a ';
Arr[1] = ' B ';
ARR[2] = ' C ';
ARR[3] = ' C ';
ARR[4] = ' e ';

For (i in arr) {

  if (arr[i] = = ' C ') {
    arr.splice (i,1);
    i=i-1;  This line of code is invalid and the value of I does not change

  }
  alert (arr.length);
}
</script>

This article discusses the use of the splice function in the array of elements to delete the note is small set to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

Related Article

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.