0
var name"X" = {
   data: blah blah blah
}

where x is a random generated number

3
  • 1
    No, but you can have an Object with a bunch of properties. const name = {}; name[Math.floor(Math.random()*Date.now())] = {data:'blah blah blah'} Keep in mind that numeric Object properties which are not instanceof Array will be converted to Strings, though. Commented Feb 6, 2020 at 2:21
  • Why do you think you need this? You typically can do what stackslave suggested Commented Feb 6, 2020 at 2:26
  • But yes, eval does what you are asking for if you have complete control of the input Commented Feb 6, 2020 at 2:30

2 Answers 2

1

you can use eval():

var k = 'value'; 
var i = 0; 
for(i = 1; i < 5; i++) { 
    eval('var ' + k + i + '= ' + '{ abc: ' + i + ' }'  + ';'); 
} 
alert(value1.abc); 
alert(value2.abc); 
alert(value3.abc); 
alert(value4.abc); 

or Window object:

var i; 
for(i = 1; i < 5; i++) { 
    window['value'+ i ] = { abc: i}; 
} 

alert(value1.abc); 
alert(value2.abc); 
alert(value3.abc); 
alert(value4.abc);  
Sign up to request clarification or add additional context in comments.

1 Comment

The window suggestion will always create global variables, but what the OP posted could create local variables if within functions. It also doesn't work on nodeJS.
0

You can't do this for the variable itself, but you could have an object with random fields.

var myValues = {
  ["name" + Math.random()]: "blah"
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.