Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  146] [ 6]  / answers: 1 / hits: 15279  / 12 Years ago, sat, january 5, 2013, 12:00:00

I'm trying to create a new object for each item in an array by looping. The names of the objects should be based on the key of the array.



So for this array:



var arr = new Array(
some value,
some other value,
a third value
);


Would result in three objects:



alert(object1.value);
alert(object2.value);
alert(object3.value);


The code I have thus far (but isn't working) is:



// Object
function fooBar(value) {
this.value = value;
...
}

// Loop
var len = arr.length;
for (var i = 0; i < len; i++) {
var objectName = object + i;
var objectName = new fooBar(arr[i]);
}


Does what I'm asking for even make sense?


More From » javascript

 Answers
33

You have to make an array of the objects also



var objs = new Array();

for(var i = 0; i < len; i++) {
objs[i] = new fooBar(arr[i]);
}

alert(objs[0].value);

[#81057] Friday, January 4, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elijahm

Total Points: 674
Total Questions: 124
Total Answers: 79

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;