Generate x number of objects - javascript

A desired x number of objects is to be created.
The system creates x number of objects.
for (i = 1; i <= x; i++) {
let obj = new Object()
}
I cannot seem to figure out how this can be done without the objects having the same name. I thought that naming them obj1 to objx using iteration to avoid conflicting names is a solution. However I do not know how to name objects and variables using the iteration number as part of its name.

You are looking for an array that holds all the different objects. In your loop, you can push the object to that array:
const objects = [];
for(let i = 1; i <= x; i++) {
let obj = {};
objects.push(obj);
}
Now you can get a certain object as:
objects[5] // the sixth object
Or you can go over all objects as:
for(const obj of objects)
console.log(obj);

As I understood you would like to be able dinamically create variables with different names.
It is possible but it is bad practice because we create global variables
for (i = 1; i <= x; i++){
window['obj' + i] = {i}; //iterate name
}
after that you can call obj1, obj2, ... and they are all global
I recommend to use local object or Map
const localObj = {};
for (i = 1; i <= x; i++){
localObj['obj' + i] = {i};
}
then you just write localObj.obj1, localObj.obj2 ...
const localMap = new Map();
for (i = 1; i <= x; i++){
localMap.set('obj'+i, i);
}
To get your data: localMap.get('obj1'), localMap.get('obj2') ...

Related

Javascript : generate variable by for loop

Am I able to use for loop to declare variables? Because declaring variables with similar one by one is not smart.
For example if I want variables like: DATA1, DATA2 and DATA3, I will normally declare it like below:
var data1 = "";
var data2 = "";
var data3 = "";
And the below is what I expect we can do in the actual code.
Using for loop and using "i" to assign number for each variable.
for(var i = 0; i < 3 ;i++){
var data+i = "";
}
am I able to do that? I suppose the above code is not the correct way to do that but just a concept.
You can define Object or Global variable.
var variables = {};
for (var i = 0; i < 3; i++) {
variables['data' + i] = i;
}
console.log(variables);
// you can use it like variables.data0
// by the way you can define global variables as you want
// but note that this pollutes the global space
for (var i = 0; i < 3; i++) {
window['data' + i] = i;
}
// so you can use it like
console.log(window.data0, ' or ', data0)
Because of the fact that javascript is dynamically typed you can do something like that. JavaScript gives you the possibility of accessing variables through a key.
var baseVariable = {};
for(var i = 0; i < 3; i++){
baseVariable["data" + i] = "ValueForData" + i;
}
You can than access these variables pretty easy by iterating through the baseVariabel, or if you now the exact amount you can even call it like that:
baseVariable.data1
You can use eval function to evaluate code from string.
For example:
var a = 2; eval('alert(a)');
Take a look at assignment chain. May be is would be suitable.
var a = b = c = d = e = f = g = "";
But this ways is not a good practice.
As mentioned in comments for your question better way to use array or object to store data.

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}

How to create javascript variable with other variable value in name

Hi I need to create a load of variables in a javascript loop so say my loop goes round 5 times starting at 0 by the end of it the following variables should be defined:
variable_0
variable_1
variable_2
variable_3
variable_4
Can anyone tell me how to do this please?
This will create "global" variables by registering them on the window object:
for (var i = 0; i != 5; ++i) {
window['variable_' + i] = null;
}
It's not really nice to do that though =/ a better way is to define an object in which you create dynamic properties.
var obj = {}
for (var i = 0; i != 5; ++i) {
obj['variable_' + i] = null;
}
console.log(obj.variable_0); // null
Why not just use an array:
var variable = [];
If you really want to create 5 variables, you need to choose the scope of them, the easiest is probably window, then you can use the sqare bracket syntax:
for(var i=0;i<5; i++){
window["variable_" + i] = 0; // or anything really!
}
Now the following variable is available:
window.variable_1 = 123
You can only create variably named variables as part of an Object:
obj['variable_' + i] = value;
There's no equivalent for function scoped variables, although you can of course do:
function foo() {
var obj = {};
for (var i = 0; ... ) {
obj['variable_' + i] = value;
}
}
You can fake global variables (but shouldn't) by using the window global object in place of obj, as shown by #Jack.
Of course in most circumstances (and since you're using numbers to differentiate the variables) what you should really do is use an array:
var myvar = [];
for (var i = 0; i < n; ++i) {
myvar[i] = ...;
}

creating numbered objects from a constructor in javascript

I have a constructor that makes squares.
I would like my code to automatically create squares from this constructor using loops and name them square1, square2, square3 ect.
eg.
for (n=1; n < x; n++){
var square(n) = new Square();
}
Is this possible?
If so how and how do I refer to them in a loop - like square(n)?
I'm new to programming, oop and javascript so sorry if this is really ovb.
thanks in advance
That's what Arrays are for:
var squares = new Array();
for (var n = 1; n < x; n++) {
squares.push( new Square() );
}
Now you're able to access them with their zero-based index:
squares[0].someMethod(); // etc..
To iterate over all the squares in that array:
for (var i = 0; i < squares.length; i++) {
squares[i].someMethod();
}
That's a pretty nasty idea. Use an array for this purpose:
var squares = [];
for (var n = 1; n < x; n++) {
squares.push(new Square());
}
Anyway, if you really want to do it:
window['square' + n] = new Square();
This will create globals. There is no clean, eval-less way to create locals like that.

Categories

Resources