0

I'm kind of new ... so go easy on me. This is what I want to do:

I have variables named:

var item1, item2, item3, etc.;

I want to use a For loop to asign values to the variables. Like this:

for(var i = 0; i < 5; i++){ item + (i+1) = arr[i] }

How can I do this without getting the Invalid left-hand side in assignment error?

Thank you.

Kapn0batai
  • 215
  • 1
  • 9
  • 1
    If those variables are local, then there is no way to access them "dynamically". Nor should you. Whenever you have variables of the form `prefixX`, then you should use an array or object instead. Since you already seem to have an array, you should change the code that reads `itemX` to work with an array instead. And FYI, `item + (i+1)` will increase `i` by one and add the result to the value of the variable `item`. – Felix Kling Jun 25 '13 at 07:57
  • You can't use this `item + (i+1)` for variable names – Balint Bako Jun 25 '13 at 07:57
  • I especially like [this answer](http://stackoverflow.com/a/6343596/218196): *"Q: What is the use of Dyanmic variables? A: For when people haven't heard of objects or arrays."* – Felix Kling Jun 25 '13 at 08:14
  • @FelixKling Hey, I said take it easy! – Kapn0batai Jun 25 '13 at 08:25
  • I did, didn't I? Provided you with all sorts of information. – Felix Kling Jun 25 '13 at 08:27

2 Answers2

1

Perhaps you could make use of a "namespace"/object like this:

var app={ item1: undefined, item2: undefined }
for(var i=1; i<3; i+=1) app["item"+i]=666;
console.log(app);

In this case, it is no "real" namespacing, but you could use it like that.

For more about Namespacing read this Article from Addy Osmani.

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
  • Using an object is ok, but why talk about namespacing at all? It has nothing to do with this question/answer. – Felix Kling Jun 25 '13 at 08:08
  • Yes. As I said, it is no namespacing in the strict sense - more something than an initial step towards namespacing. In a wider sense it behaves like one. On the one hand you could say, "item1" is a property of "app" and on the other hand, you could think of it like "variable »item1« from the namespace »app«". – Thomas Junk Jun 25 '13 at 08:24
  • Well, yeah, you *can* use objects as namespaces, but this is a bit far fetched here IMO. If I was a beginner, I would find it rather confusing. Here you are using an object as a map, nothing more and nothing less. No need to make it overly complicated. – Felix Kling Jun 25 '13 at 08:26
  • Perhaps you're right ;) A bit far fetched. – Thomas Junk Jun 25 '13 at 08:29
0

If it is a global variable, then you can do this:

var item1 = 5;
alert(window["item" + 1]);
Balint Bako
  • 2,500
  • 1
  • 14
  • 13