views:

306

answers:

2

Hi, I want to add new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:

var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;

alert(myObj.string1); //returns 'undefined'
alert(myObj.a); //returns 'string2'

In other words: How to create an object property and give it the name stored in the variable but not the name of the variable itself? Thanks.

+2  A: 

There's the dot notation and the array notation, which are equivalent.

myObj[a] = b;
philfreo
They're not really "equivalent"; `myObj.a = b` means something different to `myObj[a] = b` (unless `a == 'a'`) but whatever... this is what you want.
Dominic Cooney
What I meant is that they're equivalent ways to set a property. Obviously they behave differently (hence the purpose of posting this answer) - but they have the same result.
philfreo
A: 

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)

(alerts "whatever")

altCognito