473,503 Members | 11,237 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arrays passed by reference

Dormilich
8,658 Recognized Expert Moderator Expert
Hi,

I’m currently doing a fun project, where I stumble upon the quite annoying fact, that between some methods the arrays (they are the parameters) are passed by reference, which screws up the logic.

does anyone have an idea, how I can pass the arrays by value?
Expand|Select|Wrap|Line Numbers
  1. GAME.MagicSquare.prototype.createTable = function ()
  2. {
  3.     var doc    = document,
  4.         // create various HTMLElements
  5.         rows   = this.rows, 
  6.         cols   = this.columns, 
  7.         arr    = [],
  8.         i, j, tr_i, td_j, num, range, values;
  9.  
  10.     range = (rows * cols);
  11.     // create the result array necessary for win test
  12.     this.result = [];
  13.     for (i = 1; i < range; i += 1) {
  14.         this.result.push(i);
  15.     }
  16.     // create mixed and valid configuration
  17.     do {
  18.         // couldn't get it to be passed by value
  19.         for (i = 0; i < range; i += 1) { // fix for problem #1
  20.             arr.push(i);
  21.         }
  22.         values = this.scramble(arr); // <-- problem #1
  23.     }
  24.     while (this.unsolvable(values)); // <-- problem #2
  25.  
  26.     // create the table
  27.  
  28.     return table;
  29. };
  30.  
  31. GAME.MagicSquare.prototype.scramble = function (a)
  32. {
  33.     var i, index,
  34.         values = [];
  35.  
  36.     for (i = a.length; i--;) {
  37.         index = Math.round(Math.random() * 100 * i) % i;
  38.         values.push(a.splice(index, 1)[0]);
  39.     }
  40. // a is now [] and in the calling function arr also is []
  41.     return values;
  42. };
  43.  
  44. GAME.MagicSquare.prototype.unsolvable = function (a)
  45. {
  46.     var i, j,
  47.         inversion = 0, 
  48.         l    = a.length, 
  49.         zero = a.indexOf(0), 
  50.         cols = this.columns;
  51.     // move the 0 to the last row
  52.     j = l - cols;
  53.     while (zero < j) {
  54.         a[zero] = a[zero + cols];
  55.         a[zero + cols] = 0;
  56.         zero += cols;
  57.     }
  58. // again, in the calling function, the array (named values) always has the 0 in the last "row"
  59.     // determine number of values, that are placed after its successors
  60.     for (i = 0; i < l; i += 1) {
  61.         for (j = i + 1; j < l; j += 1) {
  62.             if (a[i] > a[j] && a[j] > 0) {
  63.                 inversion += 1;
  64.             }
  65.         }
  66.     }
  67.     // even number of "inversion" means solvable
  68.     if (1 === (inversion % 2)) {
  69.         return true;
  70.     }
  71.     return false;
  72. };
btw. tested in FF 3.6, Chrome (Opera quit due to Date.now()) / Mac
Mar 11 '10 #1
8 2240
gits
5,390 Recognized Expert Moderator Expert
yes ... arrays and objects are passed 'by reference' so therefor a deep-cloning function like this will do a deep copy of a passed object ... when you have 'flat' objects/arrays, i mean one level of values and not objects ... then even a concat() would work to copy the array ... but when a member itself is an object then even this would pass a reference to the new object ...

kind regards
Mar 11 '10 #2
Dormilich
8,658 Recognized Expert Moderator Expert
thanks gits, I prototyped an array clone, that solves my problems.
Expand|Select|Wrap|Line Numbers
  1. Array.prototype.clone = function ()
  2. {
  3.     var i, c = [];
  4.     for (i = this.length; i--;) {
  5.         if (i in this) {
  6.             c[i] = this[i];
  7.         }
  8.     }
  9.     return c;
  10. };
Mar 11 '10 #3
gits
5,390 Recognized Expert Moderator Expert
yes ... for 'flat' arrays it will do :)
Mar 11 '10 #4
Dormilich
8,658 Recognized Expert Moderator Expert
I only use "flat" arrays in this case.

wanna try it? play here.

tested FF / Chrome / Opera / Safari – Mac, definitely not working in IE
Mar 11 '10 #5
Dormilich
8,658 Recognized Expert Moderator Expert
@gits
that is, everything that is not a primitive?
Mar 11 '10 #6
gits
5,390 Recognized Expert Moderator Expert
... nearly ... functions are not 'primitives' but are even copied instead of referenced ... which is a bit confusing ...
Mar 11 '10 #7
Dormilich
8,658 Recognized Expert Moderator Expert
does that mean that, in case of event handlers via addEventListener(), the function body is copied to the element (or whereever the handler is stored)?
Mar 11 '10 #8
gits
5,390 Recognized Expert Moderator Expert
that seems a bit tricky/unclear ... in case you do:

Expand|Select|Wrap|Line Numbers
  1. var foo = function() {
  2.     alert('bar');
  3. }
  4.  
  5. node.addEventListener('click', foo, true);
i think it passes a reference since we created one before ... when you then do:

Expand|Select|Wrap|Line Numbers
  1. foo = function() {
  2.     alert('foobar');
  3. }
  4.  
  5. othernode.addEventListener('click', foo, true);
the old ref is dropped but the first click-handler has the old foo-function while the othernode will have the new foo-function assigned. so in javascript it seems that basicly it doesn't really pass by reference but i seems more likely to pass a value of a reference or similar ... so that you could drop references like above but the old 'content' persists in an anonymous context then ... hopefully that makes any sense :) ... i think this seems like closures are supposed to work ...

an example of this behaviour is as follows:

Expand|Select|Wrap|Line Numbers
  1. var a = {
  2.    foo   : { test: 1, test1: 2 },
  3.    bar   : function(a) { alert(a) },
  4.    foobar: 'foobar1',
  5.    arr   : [1, [8, 9], {1: 1, 2: 2}, 4]
  6. };
  7.  
  8. var b = {};
  9.  
  10. b.bar = a.bar;
  11. b.arr = a.arr;
  12.  
  13. // alerts 2
  14. a.bar(2);
  15.  
  16. b.arr[1] = ['foo'];
  17.  
  18. b.bar = function(a) { alert(a + a) };
  19.  
  20. // alerts 2
  21. a.bar(2);
  22.  
  23. // logs the array ['foo'] even for obj a
  24. console.log(a.arr)
  25.  
here are the references dropped too - the function is 'new' in b but 'old' in a while the references in the b.arr-array persists and the new value 'foo' then is reflected in both arr-arrays of a and b

kind regards
Mar 11 '10 #9

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

Similar topics

5
12596
by: harry | last post by:
I have 2 multi-dim arrays double subTotals = null; String rowTitles = null; I want to pass them to a function that initialises & populates them like so - loadData( rowTitles, subTotals);
19
2821
by: Canonical Latin | last post by:
"Leor Zolman" <leor@bdsoft.com> wrote > "Canonical Latin" <javaplus@hotmail.com> wrote: > > > ... > >But I'm still curious as to the rational of having type >...
5
3052
by: Gent | last post by:
I have two questions which are very similar: Is it possible to return an object in C++. Below is part of my code for reference however I am more concerned about the concept. It seems like the...
27
2582
by: Mike P | last post by:
I will be passing my function a two dimensional array of varying length. Within that array is one data point, and the number of times it should loop through. So, for example, I might pass this...
1
3427
by: Kurt Richardson | last post by:
Hi all Sorry to bother you with what is probably a really trivial question for you C++ experts. My programming skill are pretty amateur, but I'm pretty good at VB.NET. However, I'm wanting to...
11
8092
by: John Pass | last post by:
Hi, In the attached example, I do understand that the references are not changed if an array is passed by Val. What I do not understand is the result of line 99 (If one can find this by line...
64
3363
by: Zytan | last post by:
I know there are no pointers in C#, but if you do: a = b; and a and b are both arrays, they now both point to the same memory (changing one changes the other). So, it makes them seem like...
9
2425
by: Jack | last post by:
If I don't specify "ref" in the argument list when passing an array to the callee, I am passing the array (reference) by value. But this makes me confused because it actually means a "reference" of...
11
3333
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
8
1774
by: jodleren | last post by:
Hi! I have a function, a part of my code which I can use as a function. It will return 2 arrays, and I am wondering what way to do so. Both arrays hold strings, there are no special keys. 1)...
0
7194
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7316
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6976
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5566
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4993
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3160
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1495
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
372
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.