Reputation: 323
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];
}
Upvotes: 0
Views: 113
Reputation: 4906
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.
Upvotes: 1
Reputation: 439
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.
Upvotes: 1
Reputation: 6398
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.
Upvotes: 1