how do you loop through javascript numbered variables?
let count = 5;
var test1 = "test1"
var test2 = "test2"
var test3 = "test3"
var test4 = "test4"
var test5 = "test5"
for (let i = 0; i < count; i++)
{
console.log(test{i}); //no that don't work
}
tired a few different for loops I found but could not get anything to work.
New to all of this.
expecting to see the variable names…
test1
test2
test3
test4
test5
Maybe I’m asking the wrong question. The problem with an Object or an Array is when I assign it to Local Storage and go back and want to delete that item, if it’s in a array or object I delete everything using removeItem(keyName). That is why I wanted to created a new name/variable for each event. That way I can delete the item without removing everything else. –
jondavis4
5
Answers
The correct answer is
It would be good if you change variables to a data structure that allows for easy iteration like an array, or an object.
But If you have to loop over those variables, You could use the global
window
:Using the right data structure is the best option:
Array
Object
The solution most similar to your current code would be to use template variables (backticks) and the eval function, which turns a string into a var name.
Explained in-line in the code.
The problem with an Object or an Array is when I assign it to Local Storage and go back and want to delete that item, if it’s in a array or object I delete everything using removeItem(keyName). That is why I wanted to created a new name/variable for each event. That way I can delete the item without removing everything else.
Probably needs some more refinement, but i think this would solve the issue stated:
Maybe some explanation:
By using saveEvent(event) you would be able to either save a new event to the existing object inside the localStorage or create a new object if none exists. What the actual event-object would look obviously depends on your needs.
By using deleteEvent(eventName) the Object is read from the localStorage, if it exists, and the event is being removed from the retrieved object. After that the modified object is saved again inside the localStorage.