vkosyj vkosyj - 16 days ago 8
Javascript Question

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);
}

});

Answer

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