I'm looping through an array using the jquery each function. I assign a temp variable for it to loop through instead of the actual array itself as I am modifying the original array using splice. However, it looks like temp is getting modified even when I splice array.
function example (Data, index, array) {
var temp = array;
$.each(temp, function(i, v) {
if(Data["b"+v].length > index) {
//do stuff
} else {
array.splice(i,1);
}
});
if(array.length > 0) {
example(Data, index+1, array);
}
}
array = [1,2,3,4]
Data = {"b1":[a,b,c,d],"b2":[e,f,g,h], "b3":[i,j], "b4":[k,l,m,n]};
example(Data, 0, array);
On the third call of example, on the 4th iteration of temp, v becomes undefined and therefore the next line pumps out an error of "cannot read length of undefined". This happens right after array.splice(3,1) is called which seems like temp is pointing to the same place as array instead of being a copy of it.
Can anyone help?