Build Objects In For Loop With Javascript
I am trying to dynamically build an object for every iteration of a for loop using the i as part of the object name. based on the example below I would like 19 objects with names:
Solution 1:
Unless bar{i}
is an array value / object property itself the only way to do this is to bind it to the window or root object.
window[bar+i] = {};
Or to the root object
this[bar+i] = {};
Much better to bind it to an array / object itself though rather than bind senselessly to the root/window.
vararray = [];
array[bar+i] = {};
Solution 2:
There are some hacks how you can achieve this. However I advice you to use arrays instead of that method you are trying to use:
console.log(foo.length); // 19var variables = [];
for (var i = 0; i < foo.length; i++) {
variables[i] = {};
};
console.log(variables[0]);
console.log(variables[1]);
// ...console.log(variables[18]);
Solution 3:
You can't create variables like this.
What you can do is add properties of the global scope, which you can use as variables:
for (var i = 0; i < foo.length; i++) {
window['bar'+i ] = {};
};
or use another object to hold everything:
var container = {};
for (var i = 0; i < foo.length; i++) {
container['bar'+i] = {};
};
Solution 4:
You can't dynamically write variable names, but you can do the same on object properties:
console.log(foo.length); // 19var obj = {};
for (var i = 0; i < foo.length; i++) {
obj[ 'bar' + i ] = {};
};
console.log(obj.bar1);
console.log(obj.bar2);
// ...console.log(obj.bar18);
Solution 5:
You can use eval:
eval('var bar'+i+' = {};');
But really, you shouldn't be doing this, unless you know for sure you can't do it the other way.
Post a Comment for "Build Objects In For Loop With Javascript"