1

I have an issue I cant get to the bottom of, so any help would be much appreciated.

  • A the top of my scipt I declare a global value ('_raw')
  • (Using jQuery) I make an Ajax call, which returns JSON array data (I have checked, the JSON data is correct)
  • I take this JSON response and assign it to _raw
  • When I click a link, _raw gets passed to a function, e.g. function myFunction(dataArray), called with myFunction(_raw)
  • Within this function, based on some criteria, dataArray is spliced (i.e. dataArray.splice(2,1))
  • dataArray is then returned.

e.g.

var _raw;

// AJAX call sets RAW to an array e.g. Apple, Banana, Pear, Pineapple, Coconut, Raspberry

myFunction(dataArray){
  var data=dataArray;
  data.splice(2, 1);
  return data[0];
}


$('a').click(function(){

  result = myFunction(_raw);
  alert(result);
// First time this is run, returns 'Pear', however, second time, returns 'Coconut'- as if the splice is being performed on _raw as well as myArray/data...

});
  • I appreciate there is some poor code above, this is more to illustrate the issue

The problem I have, is that as far as I can see, the only time _raw is set, is during the AJAX call, however, when the function myFunction is called, passing _raw, the splice also seems to effect _raw itself. Why is this happening?

Rob W
  • 341,306
  • 83
  • 791
  • 678
SW4
  • 69,876
  • 20
  • 132
  • 137
  • arrays are passed as reference in javascript , so arrays are pointers , like objects , functions , ect ... you can use array.slice to return a new array however. – mpm Apr 04 '12 at 11:03

3 Answers3

2

Arrays are passed by reference, so var data = dataArray does not copy the array.
So, data.splice(2,1) modifies the original array.

Use .slice(2,1) to copy the array.
Or, since it seems that you want to get second element's value, use the numeric indices:

function myFunction(dataArray){
    return dataArray[2];
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
2

splice() changes the original array: see http://www.devcurry.com/2010/12/slice-and-splice-in-javascript.html

Unlike slice(), the splice() method modifies the original array and returns a new array.

As a sidenote, you don't really need to pass _raw as argument of myFunction() since it's a global variable and thus is visible everywhere

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

In JavaScript, arrays are always passed by reference, so when you assign it to the data variable, you are just creating a pointer to _raw and all operations will be done on _raw.

You need to make a clone of the array. Depending what's in it and whether it's multidimensional, you may need to use a method that will do a deep copy as per here.

Community
  • 1
  • 1
Matt Gibson
  • 14,616
  • 7
  • 47
  • 79