0

Is there any way to create variables with dynamic name? for example : i_1, i_2, i_3, ... in which 1,2,3 numbers come from a for-loop. I tried this code but unfortunately does not work:

for(let i=0; i<10; i++) {
    let `varibale_${i}` = 'some value';
}

UPDATE: I edited the code in this way based on suggestions in comment section but it does not work. Any suggestion really appreciated.

Is it possible to define these events in an object in global scope? Suppose we have these event listeners:

peer1.on('stream', () => console.log('do something'));
peer2.on('stream', () => console.log('do something'));
peer3.on('stream', () => console.log('do something'));

is it possible to define these events in an object like:

let obj = {
    peer1: on('stream', () => console.log('do something')),
    peer2: on('stream', () => console.log('do something')),
    peer3: on('stream', () => console.log('do something')),
}
roya ahmadi
  • 3
  • 1
  • 4
  • 2
    Why do you think you need to do this? Use arrays if you're just incrementing a number in the variable, and objects if the names are arbitrary strings. – Barmar May 07 '21 at 23:47
  • I do need this solution for other purpose! – roya ahmadi May 07 '21 at 23:49
  • 1
    Why? How do you use the variables that are created dynamically? – Barmar May 07 '21 at 23:50
  • I store some objects inside another object (let's say a parent object). these child objects have a property in which I need to set some kind of event listener. I'm thinking to make this property for all child objects as a global variable and set event listener to it. this property needs to have unique name for each child object in global scope. that's why I need this technique. – roya ahmadi May 07 '21 at 23:55
  • **this property needs to have unique name for each child object in global scope** No it doesn't. Put all the properties in a single global array or object, and then index it using the unique name. – Barmar May 08 '21 at 00:09
  • Oh got it, Thank you man! – roya ahmadi May 08 '21 at 00:13
  • By doing `window[ myVarName ] = value;`, althought I put this in comment because I would not recommend that, but this answrers your question – savageGoat May 08 '21 at 00:14

0 Answers0