By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,967 Members | 1,219 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,967 IT Pros & Developers. It's quick & easy.

Passing and copying arrays by value. How-to?

P: 2
I have this function
Expand|Select|Wrap|Line Numbers
  1. function test(n)
  2. {
  3.    alert(n[0]);
  4.    var a = n;
  5.    a.shift();
  6.    alert(n[0]);
  7. }
then I run this:
Expand|Select|Wrap|Line Numbers
  1. test(Array(1,2));
The first alert says:
Expand|Select|Wrap|Line Numbers
  1. 1,2
but the second says:
Expand|Select|Wrap|Line Numbers
  1. 2
How can I pass by value, or copy an array by value? I can't understand memory management in javascript.
Sep 24 '08 #1
Share this Question
Share on Google+
5 Replies

rnd me
Expert 100+
P: 427
array are always passed by ref.

one way around it:


var a = n;


var a = [].concat(n);


your test function uses the same array.
shift both returns the bottom element and removes it from the array.

thus, index 1 becomes index 0 after the shift, and you see 2 instead of 1 and 2 because 1 is gone.
Sep 24 '08 #2

P: 2
Oh, I see. Thank you for the tip.

With you answer I've created this simple function:
Expand|Select|Wrap|Line Numbers
  1. function copyArray(a,b)
  2. {
  3.    var n=a.length;
  4.    for(var i=0;i<n;i++)
  5.    {
  6.       b[i]=a[i];
  7.    }
  8. }
As the only way to "copy" an array, don't you?

I've found this better function:

I hope it helps.
Sep 24 '08 #3

rnd me
Expert 100+
P: 427
must faster to do:
Expand|Select|Wrap|Line Numbers
  1.  function copyArray(a,b) {
  2.  b= [].concat(a);
  3. }
Sep 24 '08 #4

P: 30
Yeah, it's a bit of an old thread, but just in case anyone else bumps into it... a smarter way to implement this would be as an Array method, not a simple function:

Expand|Select|Wrap|Line Numbers
  1. Array.prototype.copy = function () {
  2.    return [].concat(this);
  3. }
Then, it becomes a method of every Array. Easy to read, simple to remember:

Expand|Select|Wrap|Line Numbers
  1. var myArray = [1,2,3,4,5];
  2. var myArrayCopy = myArray.copy();
Now, I've got to go change my own Array.copy() helper-method. I'd been using a for/in loop. I don't know why I didn't think of concat() or similar.
Dec 22 '08 #5

rnd me
Expert 100+
P: 427
i think that if we are to pollute a global namespace like Array, we should have a very good reason for doing so, more than just renaming concat copy...

you don't need an extra copy method, or a blank array, just use concat or slice:

Expand|Select|Wrap|Line Numbers
  1. var myArray = [1,2,3,4,5];
  2. var myArrayCopy = myArray.concat();
Dec 22 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.