json in array -> overlap problem

P

pistacchio

hi to all!

i have the following code (i stripped down the code to a short
example, but still it does reproduce the problem):

var objs = new Array();
obj = {
parameter : " "
}

objs[0] = obj;
objs[0].parameter = "apple";

objs[1] = obj;
objs[1].parameter = "banana";

alert(objs[0].parameter);

i create a json object (obj) and insert into 2 items of a previously
created array (objs[0] and objs[1]). inspecting the array, i expect
objs[0].parameter to be "apple", not "banana", which is what i keen on
getting.
any idea?
tia, gustavo
 
D

d d

pistacchio said:
i create a json object (obj) and insert into 2 items of a previously
created array (objs[0] and objs[1]). inspecting the array, i expect
objs[0].parameter to be "apple", not "banana", which is what i keen on
getting.

objs[0] and objs[1] are both pointers to obj. You're not creating new
instances of obj, you're creating new references to the obj object.

Define obj like this:

obj=function(){this.parameter="";}

and in your array, do this:

objs[0] = new obj();
objs[0].parameter = "apple";

objs[1] = new obj();
objs[1].parameter = "banana";

~dd
 
D

Douglas Crockford

pistacchio said:
hi to all!

i have the following code (i stripped down the code to a short
example, but still it does reproduce the problem):

var objs = new Array();
obj = {
parameter : " "
}

objs[0] = obj;
objs[0].parameter = "apple";

objs[1] = obj;
objs[1].parameter = "banana";

alert(objs[0].parameter);

i create a json object (obj) and insert into 2 items of a previously
created array (objs[0] and objs[1]). inspecting the array, i expect
objs[0].parameter to be "apple", not "banana", which is what i keen on
getting.
any idea?

var objs = [
{parameter: 'apple'},
{parameter: 'banana'}
];
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,416
Latest member
LionelQ387

Latest Threads

Top