When a user clicks a button, I'm grabbing the availableTags
array, storing it in a new var tagsToWorkWith
. I then iterate over tagsToWorkWith
and run moveTag()
on each row in order to move every tag that was in availableTags
.
Inside of moveTag()
, I'm removing that row from availableTags
using splice()
. However, for some reason, this is removing the row from tagsToWorkWith
, which causes my for()
function to only run moveTag()
on every other row.
Why is splice()
removing the row from tagsToWorkWith
? I'm explicitly setting tagsToWorkWith equal to the original availableTags
to avoid this problem, but that doesn't seem to be working.
The below code runs with the error at http://jsfiddle.net/EdnxH/
var availableTags = [{"label":"Label A","value":"1"},{"label":"Label B","value":"2"}, {"label":"Label C","value":"3"}];
$(document).on('click', '#clickButton', function () {
var tagsToWorkWith = availableTags;
for(var countera=0; countera< tagsToWorkWith.length; countera++) {
alert(tagsToWorkWith[countera].label);
moveTag(tagsToWorkWith[countera].label, tagsToWorkWith[countera].value);
//This should match the first alert label, since we haven't increased the counter yet. But, for some reason, moveTag()'s splice() removes the row from tagsToWorkWith.
alert(tagsToWorkWith[countera].label);
}
});
function moveTag(itemToMove, itemToMoveValue) {
var selectedTagArrayIndex = -1;
for(var counter=0; counter< availableTags.length; counter++) {
if (availableTags[counter].value == itemToMoveValue) {
selectedTagArrayIndex = counter;
}
}
if (selectedTagArrayIndex > -1) {
availableTags.splice(selectedTagArrayIndex, 1);
}
}