473,545 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Easy Variable Scope question...

I have, what should be, a simple scope problem. Can you help me fix this?

I'm trying to end up like this:
originalArray = [1,2,7] and newArray = [6,7,12].

Instead I wind up like this:
originalArray = [6,7,12] and newArray = [6,7,12].

Here's my code:

var originalArray = [1,2,7]; /* I'm pulling this from a form and want
to keep it as is, but the function modifies it */
var newArray = createNewArray( originalArray ); /* I want to wind up
with newArray = [6,7,12] */

function createNewArray( x ) {
for ( var i = 0; i < x.length; i++ ) { x[i] += 5 }
return x;
}

I've also tried this:

function createNewArray( x ) {
var y = x;
for ( var i = 0; i < y.length; i++ ) { y[i] += 5 }
return y;
}

and this:

var originalArray = [1,2,3];
var tmpArray = originalArray;
var newArray = createNewArray( tmpArray );

function createNewArray( x ) {
for ( var i = 0; i < x.length; i++ ) { x[i] += 5 } return x;
}

all with the same disasterous results.

Thanks!

Mike
Oct 28 '05 #1
13 1432

Mike P wrote:
I have, what should be, a simple scope problem. Can you help me fix this?

I'm trying to end up like this:
originalArray = [1,2,7] and newArray = [6,7,12].

Instead I wind up like this:
originalArray = [6,7,12] and newArray = [6,7,12].

Here's my code:

var originalArray = [1,2,7]; /* I'm pulling this from a form and want
to keep it as is, but the function modifies it */
var newArray = createNewArray( originalArray ); /* I want to wind up
with newArray = [6,7,12] */

function createNewArray( x ) {
for ( var i = 0; i < x.length; i++ ) { x[i] += 5 }
return x;
}

I've also tried this:

function createNewArray( x ) {
var y = x;
for ( var i = 0; i < y.length; i++ ) { y[i] += 5 }
return y;
}

and this:

var originalArray = [1,2,3];
var tmpArray = originalArray;
var newArray = createNewArray( tmpArray );

function createNewArray( x ) {
for ( var i = 0; i < x.length; i++ ) { x[i] += 5 } return x;
}

all with the same disasterous results.

Thanks!

Mike


Hi Mike,

You were very close to the solution, taking one of your solutions from
above and modified it as follows will work:

function createNewArray( x)
{
var y = new Array();

for (var i = 0; i < x.length; i++)
{
y[i] = x[i] + 5
}

return y;
}

var originalArray = [1, 2, 7];
var newArray = createNewArray( originalArray);

You were missing the following:

var y = new Array();

It was because you were referencing the same Array that was causing the
problem. If you explicitly created a new array, that will solve your
problem.

Oct 28 '05 #2
Lee
Mike P said:

I have, what should be, a simple scope problem. Can you help me fix this?

I'm trying to end up like this:
originalArray = [1,2,7] and newArray = [6,7,12].

Instead I wind up like this:
originalArray = [6,7,12] and newArray = [6,7,12].

Here's my code:

var originalArray = [1,2,7]; /* I'm pulling this from a form and want
to keep it as is, but the function modifies it */
var newArray = createNewArray( originalArray ); /* I want to wind up
with newArray = [6,7,12] */

function createNewArray( x ) {
for ( var i = 0; i < x.length; i++ ) { x[i] += 5 }
return x;
}


No matter how you assign an array variable to another variable,
you are only assigning a reference to the original array.
You need to create an entirely new array:

function createNewArray( x) {
var y=new Array(x.length) ;
for(var i=0;i<x.length; i++) {
y[i]=x[i]+5;
}
return y;
}

Oct 28 '05 #3
Thanks... got it :)

Mike
Oct 28 '05 #4
Mike P wrote:
Thanks... got it :)


The fastest way to copy an array is to use its concat() method:

var A = [1, 2];
var B = A.concat();

Done.

concat() was introduced with JavaScript 1.2, so maybe some 'version 4'
browsers won't have it, but any even remotely modern browser will.

The usual caveat applies - elements of A that are objects (arrays or
whatever) are 'copied' as references. The other solutions offered do
the same.

--
Rob
Oct 29 '05 #5
Thanks RobG.... you're quickly becoming my best friend :)

Mike
Oct 29 '05 #6
"RobG" <rg***@iinet.ne t.au> wrote in message
news:43******** *************** @per-qv1-newsreader-01.iinet.net.au ...
The fastest way to copy an array is to use its concat() method:

var A = [1, 2];
var B = A.concat();


I got this... tried it with a simple array, and it worked. Now, I've
restructured things a bit by mixing arrays and objects. And, it's broken.
Is there something that I need to do to make sure this complex mix of
objects and arrays is copied, not referenced with an object?

Here's my code:

var A = {name: "name", contents: [{a:1, b:1},{a:6, b:3}]};
var B = {name: "newname"};
B.contents = A.contents.conc at();
B.contents[0].a = 99;
document.write( "This should be 1, but it equals " + A.contents[0].a);

Thanks again, for the assist!

Mike


Nov 8 '05 #7
Mike P wrote:
"RobG" <rg***@iinet.ne t.au> wrote in message
news:43******** *************** @per-qv1-newsreader-01.iinet.net.au ...
The fastest way to copy an array is to use its concat() method:

var A = [1, 2];
var B = A.concat();
I got this... tried it with a simple array, and it worked. Now, I've
restructured things a bit by mixing arrays and objects. And, it's broken.


Only types that are passed by value (strings, numbers) will be copied,
anything passed by reference (e.g. objects, arrays, functions) will have
a referenced passed.

Is there something that I need to do to make sure this complex mix of
objects and arrays is copied, not referenced with an object?
Yes, look at what the thing is then do the right thing. The more
complex you make the stuff you put in there, the more complex the
operation becomes.

At some point you realise it is easier to create your own custom objects
(probably using a constructor) and give them the methods they need to
pass values.

Here's my code:

var A = {name: "name", contents: [{a:1, b:1},{a:6, b:3}]};
var B = {name: "newname"};
B.contents = A.contents.conc at();


For A, you may want to give it a getContents() method so you can do
something like:

B.contents = A.getContents() ;

or similar. You need to learn a bit about designing classes (although
JavaScript doesn't have classes, the concept of constructor functions
for objects is very similar) and interfaces to know how to do this properly.

Anyhow, a quick 'n dirty copy function (sorry, you'll have to tidy this
up yourself...):

function copyThing(x)
{
if ( 'number' == typeof x) return x;
if ( 'string' == typeof x) return x;
if ( 'object' == typeof x){
if (x.constructor && Array == x.constructor) {
var z = [];
for (var i=0, len=x.length; i<len; ++i){
z[i] = copyThing(x[i]);
}
return z;
}
if (x.constructor && Object == x.constructor) {
var z = {};
for (prop in x){
z[prop] = copyThing(x[prop]);
}
return z;
}
}
return 'Fell through: ' + x.constructor;
}

// Call using:
B.contents = copyThing(A.con tents);

// Just to prove we did copy B:
alert(
'A.contents[1][\'a\']: ' + A.contents[1]['a']
+ '\n' +
'B.contents[1][\'a\']: ' + B.contents[1]['a']
);

B.contents[1]['a'] *= 3;

alert(
'A.contents[1][\'a\']: ' + A.contents[1]['a']
+ '\n' +
'B.contents[1][\'a\']: ' + B.contents[1]['a']
);

Note that it doesn't deal with functions, booleans, etc. so if you want
to stuff those into objects then copy them you'll need to add more if
statements. You can write a similar function that gets the contents of
the objects and prints them out so you can check the properties/contents.


--
Rob
Nov 8 '05 #8
VK
Besides RobG answer in the above posting:

If you are interested in a versatile data serialization media you may
also check JSON way:
<http://www.crockford.c om/JSON/>

Nov 8 '05 #9
RobG wrote:
Mike P wrote:
"RobG" <rg***@iinet.ne t.au> wrote in message
news:43******** *************** @per-qv1-newsreader-01.iinet.net.au ...
The fastest way to copy an array is to use its concat() method:
var A = [1, 2];
var B = A.concat();


I got this... tried it with a simple array, and it worked. Now, I've
restructured things a bit by mixing arrays and objects. And, it's
broken.


Only types that are passed by value (strings, numbers) will be copied,
anything passed by reference (e.g. objects, arrays, functions) will have
a referenced passed.


There is no such thing as "pass by reference" in JS/ECMAScript,
object references are values.
PointedEars
Nov 8 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2655
by: YGeek | last post by:
Is there any difference between declaring a variable at the top of a method versus in the code of the method? Is there a performance impact for either choice? What about if the method will return before the variable is used? I'm trying to get an idea of whether the .NET compilers for VB.NET and C# will move all variable declaration to the...
3
1992
by: Grant Wagner | last post by:
Given the following working code: function attributes() { var attr1 = arguments || '_'; var attr2 = arguments || '_'; return ( function (el1, el2) { var value1 = el1 + el1; var value2 = el2 + el2; if (value1 > value2) return 1;
134
7781
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that means that if I misspell a variable name, my program will mysteriously fail to work with no error message. If you don't declare variables, you...
44
1989
by: Mohanasundaram | last post by:
int i = 10; int main() { int i = 20; return 0; } Hi All, I want to access the global variable i inside the main. Is there
4
14878
by: Gery D. Dorazio | last post by:
Gurus, If a static variable is defined in a class what is the scope of the variable resolved to for it to remain 'static'? For instance, lets say I create a class library assembly that is strongly name which contains the class where the static variable is defined. This library can be referenced by multiple projects. I am fairly sure the...
23
19141
by: Russ Chinoy | last post by:
Hi, This may be a totally newbie question, but I'm stumped. If I have a function such as: function DoSomething(strVarName) { ..... }
5
2223
by: somenath | last post by:
Hi All , I have one question regarding scope and lifetime of variable. #include <stdio.h> int main(int argc, char *argv) { int *intp = NULL; char *sptr = NULL;
112
5370
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions that may print some messages. foo(...) { if (!silent)
3
2030
by: SRoubtsov | last post by:
Dear all, Do you know whether ANSI C (or some other dialects) support the following: * a variable name coincides with a type name, * a structure/union field name coincides with a type name in the same file (.c + all relevant .h's)? e.g.
0
7484
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
7928
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
7440
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
7775
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...
0
5997
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5344
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
4963
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
3470
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...
0
3451
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.