views:

35

answers:

3

I am having issues with a couple arrays below and the match method. On my page I call the Checkout() function and it sets a temporary array equal to the array I've been building with different options. It then loops through the temporary array and removes html from one of the elements. The issue is that when I alert the array Remote.Cart.products before the loop it is exactly as it was built, but when I call the function again the exact same alert shows the new updated values even though I am not modifying the Remote.Cart.products array anywhere in the function.

function Checkout() {

tmp = null;
tmp = Remote.Cart.products;

alert( Remote.Cart.products );

    for ( i = 0, li = tmp.length; i < li; i++ ) {

        for ( j = 0, lj = tmp[ i ][1].length; j < lj; j++ ) { 

            tmp[ i ][1][j][1] = tmp[ i ][1][j][1].match(/<a\s+[^>]*href="([^\"]*)"[^>]*>(.*)<\/a>/i)[2];

        }

    }

}

Your help / insight is much appreciated!

A: 

"even though I am not modifying the Remote.Cart.products array anywhere in the function"

tmp = Remote.Cart.products;
...
tmp[ i ][1][j][1] = ...

It sure looks like you are.

Anonymous
+2  A: 

You are using the same array. Just a different variable that points to the same array. In memory it's the same object.

You need to rebuild the array in your loop so that you can get an identical but new array.

More info on copying arrays and other objects can be found here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165

Squeegy
Thank you for the info, I've never run across this issue before.
Clint
+1  A: 

Clint, you have to understand that tmp and Remote.Cart.products are different names for the same array. If you want to clone the array, do:

var tmp = [];
for(var i = 0; i < Remote.Cart.products.length; i++)
{
  tmp[i] = []
  for(var j = 0; j < Remote.Cart.products[i].length; j++)
  {
    tmp[i][j] = [];
    for(var k = 0; k < Remote.Cart.products[i][j].length; k++)
    {
      tmp[i][j][k] = Remote.Cart.products[i][j][k].slice();
    }
  }
}

EDIT: Nesting corrected thanks to Squeegy

Matthew Flaschen
The nested arrays would have to be copied as well though, right?
Squeegy
Works great, going to prototype the procedure as a clone or copy method. Thanks again everyone!
Clint
Clint, note that Squeegy's link contains a prototype function for cloning, and similar code is available elsewhere.
Matthew Flaschen