0
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

1
  • 1
    It's totally unclear what your intention is -- neither the code nor the description help much. Commented Jan 23, 2015 at 22:26

3 Answers 3

4
for (var i = 1; i < 10; i++) {
    var string_to_store = "string " + i;
    /* store string_to_store to localStorage */
}
Sign up to request clarification or add additional context in comments.

4 Comments

No it's absolutely fine, plus one.
That's rather obvious. It's down to the programmer to do something with the intermediate values of string_to_store.
It's totally wrong to place a variable and use it from outside the loop, as OP wanted to use localStorage...
@BhojendraNepal - The assumption is that the OP would do whatever he wanted to do inside the loop. Also, the OP's original piece of code would do nine values only ;)
2

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.

Comments

1

Like this?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.