1

I have this particular script which uses a javascript dictonary

var z= 'Bingo';
var fruit={ 'Bingo' :1};
var fruit2={ z :1};
alert(fruit[z]);
alert(fruit2[z]);
alert(fruit2['z']);

The first alert gives the expected value 1. However, the second alert gives the alert value as "undefined" and third alert gives the output as 1. Is there a way to use a variable inside a dictionary, ie. can we specify the javascript interpreter to read z as a variable rather than as string 'z'?

Thanks!

Abhinav Jain
  • 153
  • 2
  • 7
  • I believe it is unclear what you are asking. – bozdoz Oct 03 '13 at 06:48
  • This question appears to be off-topic because it is about an extremely basic feature which is covered in the first pages of any tutorial. –  Mar 08 '14 at 02:28

1 Answers1

2

Yes, you can do this easily, but not inside an object literal. Property names in object literals are taken literally. They are not variable names. JavaScript quotes them implicitly if you don't quote them.

For example, these two object literals are the same:

{ a: 1 }

{ 'a': 1 }

To use a variable, you need to use [] notation outside an object literal:

var z = 'Bingo';
var fruit2 = {};
fruit2[z] = 1;
Michael Geary
  • 28,450
  • 9
  • 65
  • 75