简体   繁体   中英

shift changes the length of the array so the last element is not going to be executed

In JavaScript, for a array, if methods such as pop, shift is used, the length of array changes as well. In my JS code below, it never executes the third elements 'Ds3' in the array since after the notes.shift() is executed, the length of the array becomes 0 so it just jumps out of the for loop, I do not know how to change the code so it can actually execute the 'Ds3'. Hope someone could help me out. Thank you in advance.

Code 1:

$(document).ready(function() {
    var notes = ['F2', 'As2','Ds3'];
    for(i = 0; i < notes.length; i++) {

        $('#_' + notes.shift()).addClass('just_do_it');
        alert(notes.length);
    }

});

For code 2, I do not know why when I sort of make the one line code to two liner, the code does not work at all. Thank you in advance. code 2:

 $(document).ready(function() {
    var notes = ['F2', 'As2','Ds3'];
    var count = 0;
    for(i = 0; i < notes.length; i++) {
        var note = notes.shift();
        $('#_' + note).addClass('just_do_it');
        count++;
        alert(notes.length);
    }

});

Is there a reason why you want to empty that array? If insist on it, try changing to a while loop.

var notes = ['F2', 'As2','Ds3'];
var count = 0;
while(notes.length > 0){
    var note = notes.shift();
    $('#_' + note).addClass('shown');
    count++;
    alert(notes.length);
}

If I may add, you're also incrementing the count as you loop through the array. Rather you can get the count immediately just by getting the length of the array like this var count = notes.length

Also since you mentioned pop and shift arrays methods, you should checkout other array methods such as forEach , map or reduce

Since shift() is indeed destructive you could simply use the index of that iteration in the loop and leave the array unaltered

for(i = 0; i < notes.length; i++) {
        // switch from `notes.shift() to notes[i]
        $('#_' + notes[i]).addClass('just_do_it');
        count++;
        alert(notes.length);// length remains unchanged
}

Or using join() to create a selector for all and not use any loop

$('#_' + notes.join(',#_') ).addClass('just_do_it');

You could also try:

for (var count = notes.length; count > 0; count--) {
        $('#_' + notes.shift()).addClass('just_do_it');
}

or

while (notes.length > 0) {
      $('#_' + notes.shift()).addClass('just_do_it');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM