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? - GAME.MagicSquare.prototype.createTable = function ()
-
{
-
var doc = document,
-
// create various HTMLElements
-
rows = this.rows,
-
cols = this.columns,
-
arr = [],
-
i, j, tr_i, td_j, num, range, values;
-
-
range = (rows * cols);
-
// create the result array necessary for win test
-
this.result = [];
-
for (i = 1; i < range; i += 1) {
-
this.result.push(i);
-
}
-
// create mixed and valid configuration
-
do {
-
// couldn't get it to be passed by value
-
for (i = 0; i < range; i += 1) { // fix for problem #1
-
arr.push(i);
-
}
-
values = this.scramble(arr); // <-- problem #1
-
}
-
while (this.unsolvable(values)); // <-- problem #2
-
-
// create the table
-
-
return table;
-
};
-
-
GAME.MagicSquare.prototype.scramble = function (a)
-
{
-
var i, index,
-
values = [];
-
-
for (i = a.length; i--;) {
-
index = Math.round(Math.random() * 100 * i) % i;
-
values.push(a.splice(index, 1)[0]);
-
}
-
// a is now [] and in the calling function arr also is []
-
return values;
-
};
-
-
GAME.MagicSquare.prototype.unsolvable = function (a)
-
{
-
var i, j,
-
inversion = 0,
-
l = a.length,
-
zero = a.indexOf(0),
-
cols = this.columns;
-
// move the 0 to the last row
-
j = l - cols;
-
while (zero < j) {
-
a[zero] = a[zero + cols];
-
a[zero + cols] = 0;
-
zero += cols;
-
}
-
// again, in the calling function, the array (named values) always has the 0 in the last "row"
-
// determine number of values, that are placed after its successors
-
for (i = 0; i < l; i += 1) {
-
for (j = i + 1; j < l; j += 1) {
-
if (a[i] > a[j] && a[j] > 0) {
-
inversion += 1;
-
}
-
}
-
}
-
// even number of "inversion" means solvable
-
if (1 === (inversion % 2)) {
-
return true;
-
}
-
return false;
-
};
btw. tested in FF 3.6, Chrome (Opera quit due to Date.now()) / Mac
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
Dormilich 8,658
Recognized Expert Moderator Expert
thanks gits, I prototyped an array clone, that solves my problems. - Array.prototype.clone = function ()
-
{
-
var i, c = [];
-
for (i = this.length; i--;) {
-
if (i in this) {
-
c[i] = this[i];
-
}
-
}
-
return c;
-
};
gits 5,390
Recognized Expert Moderator Expert
yes ... for 'flat' arrays it will do :)
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
Dormilich 8,658
Recognized Expert Moderator Expert @gits
that is, everything that is not a primitive?
gits 5,390
Recognized Expert Moderator Expert
... nearly ... functions are not 'primitives' but are even copied instead of referenced ... which is a bit confusing ...
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)?
gits 5,390
Recognized Expert Moderator Expert
that seems a bit tricky/unclear ... in case you do: - var foo = function() {
-
alert('bar');
-
}
-
-
node.addEventListener('click', foo, true);
i think it passes a reference since we created one before ... when you then do: -
foo = function() {
-
alert('foobar');
-
}
-
-
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: -
var a = {
-
foo : { test: 1, test1: 2 },
-
bar : function(a) { alert(a) },
-
foobar: 'foobar1',
-
arr : [1, [8, 9], {1: 1, 2: 2}, 4]
-
};
-
-
var b = {};
-
-
b.bar = a.bar;
-
b.arr = a.arr;
-
-
// alerts 2
-
a.bar(2);
-
-
b.arr[1] = ['foo'];
-
-
b.bar = function(a) { alert(a + a) };
-
-
// alerts 2
-
a.bar(2);
-
-
// logs the array ['foo'] even for obj a
-
console.log(a.arr)
-
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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);
|
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...
|
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...
|
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);
|
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...
| |
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...
|
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
|
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...
|
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...
|
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.
|
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...
| |
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...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |