javascript - looping through variables to create new dynamic variables
Anyone got an ideas?
I have a list of dogs as separate variables, coming from a badly formated API. Should have put the dogs in an array!
dog1 = "Poodle";
dog2 = "Greyhound";
dog3 = "Beagle";
dog4 = "Border Terrier";
dog5 = "Blood Hound";
dog6 = "West Highland Terrier";
dog7 = "Alsatian";
dog8 = "Scooby Doo";
etc...
Anyway I want to 'loop' through the dogs:
for(let i = 0; i < 20; i++) {
listDogs.innerHTML += `${dog[i]}`;
}
Obviously the above doesnt work as its not valid code but you get the idea.
I can get this working using 'eval' but am reluctant to use it because of poor write ups.
for(let i = 0; i < 20; i++) {
let dogList = eval(`dog${i}`);
listDogs.innerHTML += `<li>${dogList}</li>`
}
or I can push to an array, which I can then loop through, but is kind of long-winded and not very elegant, but more secure:
let dogList = [];
dogList.push(dog1);
dogList.push(dog2);
dogList.push(dog3);
dogList.push(dog4);
dogList.push(dog5);
dogList.push(dog6);
etc...
Is there some other solution that I'm obviously missing which creates dynamic variables like eval does (it obviously bolts a string and a variable number together to form a new variable)???
Cheers
Os
