473,568 Members | 3,014 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 2241
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 addEventListene r(), 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
12604
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
2830
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 > >pointer-to-array-of-size-N-of-type-T (which is fine) and not having type > >array-of-size-N-of-type-T (with some exceptions, which is curious). > > So far > >the consensus seems to...
5
3072
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 function below is returning a pointer to pointers who are GUID. I am trying to write a wrapper to use in my VB code and what I would prefer to do is be...
27
2593
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 to the function: example = new Array("A",2); example = new Array("Q",4); function loopIt(example);
1
3435
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 realise some of the speed benefits of writing some of my routines in C++ and accessing them from my VB software. I have managed to do this with a...
11
8103
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 number) which is the last line of the following sub routine: ' procedure modifies elements of array and assigns ' new reference (note ByVal) Sub...
64
3388
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 pointers. Can someone please explain why? thanks. Zytan
9
2433
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 a "reference"??As I pass the array by value, the callee can change that array. However,when I use ref, the callee and caller point to two different...
11
3337
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 ways of passing an array. In the following code, fun1(int a1) - same as fun1(int* a1) - where both are of the type passed by reference. Inside this...
8
1779
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) setting the arrays as globals 2) returnin an array of arrays 3) returning a large array with a known marker to indicate when the 2nd part starts.
0
7693
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8118
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7665
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5501
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2105
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 we have to send another system
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.