0

I recently started working on Java script. This question may sound silly. I have written below function. My goal is to assign each value in array to new variable. Is this is possible in js? eg: Index0 = Saab, Index1 = Volvo, Index3

function myFunction() {
  var str3 = "Index";
  var cars = ["Saab", "Volvo", "BMW"];
  var str1 = "Hello";

  for(let i = 0; i < cars.length; i++) {
    //console.log(str1 + i);
    //cars[i] = str1 + i;
    //console.log(cars[i]);
    str3 + i = cars[i];   
  }

The above function which I have written didn't return expected result. Can someone please point me in correct direction on how to properly assign values.

4
  • Don't create dynamic variables like this. Use an array instead Commented Oct 22, 2020 at 11:44
  • In normal code (ie without eval), you cannot dynamically build variable names in JavaScript. But you can add properties to objects with dynamically created names, or use a Map. Would this suffice? Commented Oct 22, 2020 at 11:48
  • I hope this is what you need, codepen.io/Maniraj_Murugan/pen/RwRoQEx Commented Oct 22, 2020 at 11:48
  • @Maniraj Creating map is good idea. I will try to implement this. Ben Thanks for suggestion Commented Oct 22, 2020 at 11:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.