0

my question is can i possibly initialize variables repeatedly (with changing only numbers after them) this is my code

for(i = truStorage.getItem('elementCount'); i>0; i--) {
var obj = truStorage.getItem("element_" + i);
var [obj_+i] =  element(erd.Entity , obj.posx, obj.posy, obj.text );}

};

basically i just want to initialize a variable like

something_i = "";

and the result will be like this

var element_1 = element(erd.Entity, 100, 200, "Employee");
var element_2 = element(erd.Entity, 100, 400, "Salesman");
var element_3 = element(erd.WeakEntity, 530, 200, "Wage");
var element_4 = element(erd.IdentifyingRelationship, 350, 190, "gets paid");

im not trying to use variables as a storage but rather to instantiate an element for a function.

4
  • 3
    Why you no use Array?!? Commented Jan 19, 2014 at 9:24
  • What are you trying to accomplish? This sounds like a bad idea, maybe we can help you with ideas :) Commented Jan 19, 2014 at 9:31
  • Everytime you come across a situation like that, just push all your objects into an array and iterate over it. Commented Jan 19, 2014 at 9:31
  • i have edited the code.. hope it explains it much better Commented Jan 19, 2014 at 9:32

3 Answers 3

2

This is a job for an array.

var something = [];
var somethings = 5;

for(var i = 0; i < somethings; i++) {
    something[i] = "";
} 

You should now be able to access the five values like this:

console.log(something[0])
console.log(something[1])
console.log(something[2])
console.log(something[3])
console.log(something[4])

Notice you use 0 to access the first element. That's just how it is because JavaScript arrays are zero-based.

Sign up to request clarification or add additional context in comments.

Comments

0

This is best scenario to use array:

var counter=0,something = new Array();
for(i = truStorage.getItem('elementCount'); i>0; i--) {
   something[counter] =  truStorage.getItem("element_" + i).text;
   counter++;
  }
};

Comments

0

Try:

for(var i=1; i<=4; i++) {
    this["something_" + i] = i;
}

console.log(something_1); //outputs 1;
console.log(something_2); //outputs 2;
console.log(something_3); //outputs 3;
console.log(something_4); //outputs 4;

Note: using an array will be faster!

1 Comment

1: use window, not this (which can change with scope and is not defined at root level in strict mode) and 2: the other questions are providing a much better answer to the problem (if not the question); you should at least note that.

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.