- 1

How can I create different objects in one loop in JavaScript?

I want to make (nested) loops to make objects called fieldA, fieldB, fieldC, ... in one loop from an ARRAY['A','B','C',...]. How can I set the object-variable-names?

7th Feb 2017, 7:21 PM
Wolfgang Kubik
Wolfgang Kubik - avatar
4 Answers
+ 3
Thumb up for finding a solution by yourself, but thumb down for the question, which was too much inaccurate: even after studying your answer, I don't see how we could deduct precisely what you was expected ^^ As answer to your questiion ( where the essential thing you missed is that you have to instanciate your objects with x/y coordinates -- and I don't see objects calles "fieldA, fieldB, fieldC, ...' in your code ), I would rather imagine something like that: var Field=function() { }; // a fake class var suffix = ['A','B','C','Z','K']; // no need to have a logic suite var fields = { }; // a basic object as a key/value array to store the objects var i = suffix.length; // an index/counter for iterate while ( i-- ) { // reverse iterate doesn't matter, as objects properties are unordered fields[ 'field' + suffix[ i ] ] = new Field(/*...args...*/); } // use whatever: alert(fields['fieldZ']); alert(fields.fieldZ);
8th Feb 2017, 1:58 AM
visph
visph - avatar
+ 2
As you are handling concept transposable to grid system coordinate, solution of array seems to be the more adapted... But you can have name 'dynamically' formed used as variable 'id' through the ability of JS to handle in same way 'object.property' notation as 'object["property"] ( means the two references the same variable/value ): it's what I done in my previous post ;)
8th Feb 2017, 2:47 AM
visph
visph - avatar
+ 1
Found a solution myself, just made a nested array of arrays filled with the objects: let board = new Array(); for (let i=0;i<8;i++) { board[i] = new Array(); for (let j=0;j<8;j++) { board[i][j] = new Field(x[i], y[j], false, false, undefined, 'black', true); if (i%2 === j%2) {board[i][j].color='white'}; } }
7th Feb 2017, 9:33 PM
Wolfgang Kubik
Wolfgang Kubik - avatar
0
At first I wanted to make 64 objects (1 for each field on a chessboard). My goal was looking like this: field00{...args...} field01{...} ... field76{} field77{} I wanted to know if there was a syntax for using variables in variable-name declarations. Having a hard time explaining this in English... for example: var a = "text" I want to create a variable called "text04" with referring to the "text" from var a. var (-> a )+"04" - something like that. Don't know if it is even possible. My solution is the way I decided to go after 2 hours of looking for this syntax... It's not the solution to my problem, but I think it works even better this way.
8th Feb 2017, 2:30 AM
Wolfgang Kubik
Wolfgang Kubik - avatar