-2

EDIT 2 : This is my first post on stock overflow and although I sometimes have some bad, questions to ask. i thought id at least fix the formatting considering I can not delete this.

I essentially wanted to automate variable creation , although at the time I did not not such things as arrays existed surprisingly.

I want to automate the creation of this variable

var l = createSprite(200,200);

I want to be able to define one variable , with another like this :

var count = 5;
var l + count = 1;
count++;
var l + count = 2;
var l=30 
var l + "foo" = 40`

if I were to run this, lfoo would be returned undefined. Why? Is this impossible? If so how can i automate defining variables?

3 Answers3

1

You could take an object and use l as part of the key for the access.

var l = 30 ,
    object = { [l + "foo"]: 40 };

console.log(object[l + "foo"]);
console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can't define variables like this. You have to define it through writing the absolute name for them. But to call them you can use window["l"+"foo"].

var l = 40;
var lfoo = 30;
console.log(window["l"]+"...."+window["l"+"foo"]);
Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
1

You could use window to declare global variables

var str = 'l' + 'foo';
window[str] = 40;
//Then you can access lfoo directly
Charlie
  • 93
  • 1
  • 6