Murad Elboudy
Murad Elboudy

Reputation: 117

How to make a for loop var with a string that increments in js

something like: for(var i="string 1"; i<10; i++){
i="string 2"
i="string 3"
}

and so on. Is it possible? Because I'm trying to store different things into the local storage using a for loop and i want each thing to start with a different key other than all being number indexes for easier extraction

Upvotes: 0

Views: 66

Answers (3)

Bathsheba
Bathsheba

Reputation: 234635

Javascript supports + as a way of concatenating a string with something else. So you can do something along the lines of

for (var i = 1; i < 10; i++)
    var s = "string " + i;

s will have the value string 1, string 2, and so on.

Upvotes: 2

gvk
gvk

Reputation: 466

for (var i = 1; i < 10; i++) {
    var string_to_store = "string " + i;
    /* store string_to_store to localStorage */
}

Upvotes: 4

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Like this?

for(var i=0; i<10; i++){
 console.log("string " + i);//logs to the console: string 0, string 1,..string 9
}

Upvotes: 1

Related Questions