1

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

jondavis4
  • 39
  • 4
  • 1
    why would you need to do that? – Chris G Jun 29 '23 at 21:08
  • 2
    Maybe change your variables to a data structure that allows for easy iteration like [an array](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays), or [an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects). – Andy Jun 29 '23 at 21:12
  • It would be too complicated to explain why. Using an array or object I don't think will help. Or at least make what I'm trying to do more complicated. It has to do with using a variable for each local storage I want to use. – jondavis4 Jun 29 '23 at 21:15
  • *'It has to do with using a variable for each local storage I want to use'* sounds like an ideal case for using an object or array, or destructuring in the right case. – pilchard Jun 29 '23 at 21:56
  • Voted to re-open as IMHO it is not a duplicate of those cited and involves getting the global keys by filtered name ending in a number here. – Mark Schultheiss Jun 29 '23 at 22:05
  • So just to understand the issue at hand: You are saving variables representing "events" in the local storage and those entries are being deleted when necessary. And the issue you see with using an object to store those events would be that every time you want to delete one entry, the entire object would be deleted aswell? – Testarea Jun 29 '23 at 22:12
  • @MarkSchultheiss This is a direct duplicate of at least 3 other long standing questions – pilchard Jun 29 '23 at 22:14
  • 1
    @jondavis4 I am pretty sure that you can easily solve this by restructuring your code to use an array. – Toxiro Jun 29 '23 at 22:26
  • @Testarea, yes that is my problem. And yes I'm still new to coding. But after using removeItem(keyName) and deleting everything in my array or objects I decided to create new variables as I go and assign them into local storage. – jondavis4 Jun 29 '23 at 22:29
  • Would my answer help you solve the issue ? – Testarea Jun 29 '23 at 22:34
  • Definitely an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). And a duplicate multiple times over. [How to delete an item from an array from localstorage onclick](https://stackoverflow.com/questions/70672745/how-to-delete-an-item-from-an-array-from-localstorage-onclick), [How to remove localstorage data by an id in an array object](https://stackoverflow.com/questions/69355288/how-to-remove-localstorage-data-by-an-id-in-an-array-object) – pilchard Jun 29 '23 at 22:53
  • The original quested was edited and now IS clearly an XY Problem; re-closing as such – Mark Schultheiss Jun 30 '23 at 12:11

4 Answers4

1

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:

function saveEvent(event){
    if(localStorage.getItem("events") != null){
        const events = JSON.parse(localStorage.getItem("events"));
        events[event.name] = event.value;
        localStorage.setItem("events",events)
    }else{
        const events = JSON.stringify({ "event1": "event description?", "event2": "another description?"})
        localStorage.setItem("events",events)
    }
}

function deleteEvent(eventName){
    if(localStorage.getItem("events") != null){
        const events = JSON.parse(localStorage.getItem("events"))
        events[eventName] = undefined;
        localStorage.setItem("events",JSON.stringify(events))
    }else{
        console.error("Events doesn't exist!")
    }
}

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.

Testarea
  • 88
  • 1
  • 6
0

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.

let count = 5;
 
var test1 = "test1"
var test2 = "test2"
var test3 = "test3"
var test4 = "test4"
var test5 = "test5"

for (let i = 1; i <= count; i++)
{
    console.log(eval(`test${i}`));  
}
symlink
  • 11,984
  • 7
  • 29
  • 50
-1

Explained in-line in the code.

let count = 5;

var test1 = "test1";
var test2 = "test2";
var test3 = "test3";
var test4 = "test4";
var test5 = "test5";
var test345 = "test7262";
// get all the window keys - might be a lot
// all the global keys
let keys = Object.keys(window);
// lots of them console.log(keys, keys.length);
/*
const PATTERN = 'test'; // pattern to filter into (might need work if "testmealso" is one
let filteredKeys = keys.filter(name => name.includes(PATTERN)); // one way
*/

// better way perhaps:
const regex = new RegExp("^test[^\d]+", 'g');
/* explained as
^test - starts with test
[^character_group] Negation: Matches any single character that is not in character_group.
\d Matches any decimal digit.
*/
console.log(window["test345"]); // the value of one
// filter then now on the regex
const matchedSites = keys.filter((key) => key.match(regex));
console.log(matchedSites);

//console.log(filteredKeys);    
// what are they:
matchedSites.forEach(key => {
  // log key/value pairs
  console.log(key, window[key]);
});
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • note: this is strictly the global variables/keys here as the question asked and does not factor in `let` or `const`.. This also has no limited number which can be factored in if needed in the loop part or otherwise. – Mark Schultheiss Jun 29 '23 at 22:07
-2

The correct answer is

let count = 5;
var tests = ["test1", "test2", "test3", "test4", "test5"];

for (let i = 0; i < count; i++) {
    console.log(tests[i]);
}