javascript - What does j-- in the second for loop mean?
三叔
三叔 2017-06-30 09:58:48
0
2
1726

var arr = [ 1,2,2,4,2 ];

for ( var i=0; i<arr.length; i++ ) {

for ( var j=i+1; j<arr.length; j++ ) {
    if ( arr[i] == arr[j] ) {
        arr.splice( j, 1 );
        j--;
    }
}

}

三叔
三叔

reply all(2)
某草草

If duplicates are encountered, splice them out of arr. After
splice is removed, the next item in the array is still the current index, so you need to first j--; and then j++ in the loop to keep the index correct.

For example, in the second outer loop, i = 1, j = 2, then arr[1] is 2, arr[2] is also 2, arr[2] will be splice out, and the array becomes [1,2, 4,2], the next element 4 is still the 2nd item, and will be missed if j-- is not done first.

代言

What you said above is correct. To add, it can be achieved directly by using filter.

var arr = [ 1,2,2,4,2 ];

arr.filter(function (e, i) {
    return arr.indexOf(e) === i;
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!