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?

有帮助吗?

解决方案

Arrays and objects are assigned by reference. temp and array reference the same array. You can create a shallow copy using .slice() [MDN]:

var temp = array.slice();

Instead of creating a copy, you could iterate over the array in reverse order:

for(var i = array.length; i--; ) {
    if(Data["b"+array[i]].length > index) {
        //do stuff
    } else {
        array.splice(i,1);
    }
}

其他提示

temp is just a reference to the same array, so temp and array are the same thing. You want to make a copy, like so:

temp = array.slice(0);

Assignments in JavaScript are by reference, it doesn't copy the object. Eg...

var obj1 = {};
var obj2 = obj1;
obj2.hello = "world";
console.log( obj1.hello ); // logs "world"

This is because obj1 and obj2 are pointing to the same object in memory.

If you want to make a copy of an array, the slice method can be used...

var arrayCopy = myArray.slice(0)

Now arrayCopy & myArray can be edited independently. However, be aware that although the arrays themselves are independent, they point to the same objects...

arrayCopy[0] === myArray[0]; // true
arrayCopy[0] = {my: "new object"};
arrayCopy[0] === myArray[0]; // now false
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top