2

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!

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.