JavaScript problems with the For loop removing the contents of an array element _javascript tips

Source: Internet
Author: User

The problem that occurs yesterday when you use a For loop to go to the weight of an array,

First, the previous and all subsequent elements are compared with the double for loop, and if equal is deleted.

However, problems can occur if there are more than three consecutive equal elements in the array.

var arr = [1,1,1,2,2];
For (Var i=0. i<arr.length-1; i++) {for
(var j=i+1; j<arr.length; J + +) {
if (arr[i] = = Arr[j]) {
Arr.splice (j,1); 
}} document.write ("arr:" +arr);

Output:

This is because when an array deletes an element, the length of the array is reduced by 1, the following element moves forward one bit, and the index is reduced by 1, but J still operates with J + +.

That is, the first delete is, i=0 j=1, delete after arr=[1,1,2,2], and then j=2, will ignore the deletion after the j=1 elements continue to traverse.

So in the case of each deletion, the J is reduced by 1

var arr = [1,1,1,2,2];
For (Var i=0. i<arr.length-1; i++) {for
(var j=i+1; j<arr.length; J + +) {
if (arr[i] = = Arr[j]) {
Arr.splice (J--, 1);
}} document.write ("arr:" +arr);

Output:

Similar to the deletion of an array element, consider that the length of the arrays will be reduced by 1, and the following elements will move forward one

The above is a small set of JavaScript for the introduction of the for loop to delete the contents of the array elements of the problem, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.