0

Is it possible to declare a variable differently for each iteration? Here is the general idea:

var userIds = [9110252, 55829847, 145189041]

    for(u = 0; u < userIds.length; u++){

        console.log(userIds[u]);

        var user+userIds[u] = userIds[u]; 
}
mellows
  • 303
  • 1
  • 7
  • 27
  • 1
    The question is why? You already have the values in an array, why would you need dynamic variable names. – adeneo May 08 '16 at 09:27
  • 1
    This is a simplification of where I am actually using localStorage, as you have to declare a variable each time to get the stored item? e.g. `var user = localStorage.getItem('user');` – mellows May 08 '16 at 09:32
  • Then you should tell us that, as with localStorage it would be completely different, all you'd do is `window.localStorage.setItem(user+userIds[u], userIds[u] )` and `localStorage.getItem(user+userIds[u]);`, no need for dynamic variable names – adeneo May 08 '16 at 09:36

3 Answers3

1

It's not possible. But you also don't need that:

You won't be generating dynamic variable names, but you can have a different variable in each iteration of the for loop:

var userIds = [9110252, 55829847, 145189041]
for(u = 0; u < userIds.length; u++){
   console.log(userIds[u]);
   var user = userIds[u]; 
}

On the first iteration, user will hold 9110252, on the second a new value is set to variable user: 55829847 and so forth.

But in this case, as @adeneo mentioned: You already have: userIds[u] to refer to the value.

Bruno Garcia
  • 6,029
  • 3
  • 25
  • 38
1

We have arrays for that .Why do u need to have different name of variable when one array variable can do it for u and also it makes code easy to manage.

Abhishek Panjabi
  • 439
  • 4
  • 23
1

Reading through the comments on the question and wanting to store it inside local storage. I would do this:

var userIds = [9110252, 55829847, 145189041];

for (var i = 0; i < userIds.length; i++) {
    var userId = 'user' + userIds[i];
    window.localStorage.setItem(userId, userIds[i]);
}

I would recommend however to reconsider this type of storage, because you're now storing redundant data. It's only distinguished with the word "user" in front of it.

User @Abhishek Panjabi also mentioned that this is the reason why we have arrays. He is correct in saying this.

Credits to user @adeno for his comment.

DevNebulae
  • 4,566
  • 3
  • 16
  • 27