0

I am trying to create a variable name based on id value of another variable. I thought this would work.

So when I click one of the 4 tables, I obtain the tables id. Example: 676.

I am then trying to create a variable using such number

var id = 66;
var 'table' + id = ''; // expecting var table66 = '';

I get error above. but if I try

var table66 = '';

it works No matter how I try adding "cans" + "66" equal to a new selector variable it will not work.

I am trying to achieve getting the id and a string. add them together to create a new variable name

David Smith
  • 147
  • 3
  • 10

2 Answers2

0

You can use the window object as an object and use bracket notation: enter image description here

id = 66;
window['table' + id] = 'test';
alert(table66); //"test"
dave
  • 62,300
  • 5
  • 72
  • 93
0

Create an object and use the variables as object properties. This will allow you to scope within a function and not pollute global window.

var id = 66;
var obj={};
obj['table' + id] = 'test';
alert(obj.table66); //"test"
charlietfl
  • 170,828
  • 13
  • 121
  • 150