PrioneJS
PrioneJS

Reputation: 21

Passing JavaScript array by value

I have a problem passing an Array of Arrays by value. I use slice() to pass a copy of the array, but the original is still modified. Here a small sample:

var test = [[1,2],[3,4]];

function addElement(data) {
    $.each(data,function(v,val) {
        val.push(1)
    });
    return data;
};

addElement(test.slice());

What am I doing wrong?

Thanks for your help!

Upvotes: 2

Views: 52

Answers (1)

ssube
ssube

Reputation: 48307

You're making a copy of the outer array, but it still contains references to all the same inner arrays. You need to make a deep copy. If you know you just have an array containing arrays, you can do something like:

var test = [
  [1, 2],
  [3, 4]
];

function copy(val) {
  if (Array.isArray(val)) {
    return val.map(copy);
  } else {
    return val;
  }
}

function addElement(data) {
  $.each(data, function(v, val) {
    val.push(1)
  });
  return data;
};

addElement(copy(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 4

Related Questions