Below is what the code looks like right now, with less rows and less properties.
var row1 = new Object();
var row2 = new Object();
var row3 = new Object();
var row4 = new Object();
var row5 = new Object();
var row6 = new Object();
var row7 = new Object();
row1.name = "Hello World!";
alert (row1.name);
This code below doesn't work as intended because row isn't primitive, but I need to do something like this because I have a billion row variables.
var row = [];
var row1 = [];
var row2 = [];
var row3 = [];
row.push(1);
row[1].name = "Hello World";
alert(row[1].name);
How can I do this, if at all possible?
-
1 billion row variables?? Not sure javascript will handle that many objects. Do you just need an array of objects? Sample 1 should work. In the second code sample your pushing an integer to an array. Then attempting to add a property. integers cannot have additional properties.Captain John– Captain John2014年01月09日 21:11:42 +00:00Commented Jan 9, 2014 at 21:11
2 Answers 2
var rows = [];
for(var i = 0; i < 7; i++)
{
rows.push(new Object());
}
rows[0].name = "Hello World!";
alert(rows[0].name);
answered Jan 9, 2014 at 21:09
Justin Niessner
246k40 gold badges416 silver badges546 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can create custom complex objects in javascript like this:
//complex object
ComplexObj = function(){
var self = {
'prop1': 'value1',
'prop2': 'value2',
'prop3': {
'subprop1': 'subvalue1',
'subprop2': 'subvalue2'
},
'prop4': [
1, 2, 3, 4
]
};
return self;
};
//code that creates instances of the complex object
var rows = [];
var newObj1 = new ComplexObj();
newObj1.prop1 = 'newvalue1';
var newObj2 = new ComplexObj();
newObj2.prop3.subprop2 = 'newsubvalue2';
rows.push(newObj1);
rows.push(newObj2);
for (var i = 0; i < rows.length; i++){
alert('row' + i + ': prop1=' + rows[i].prop1 + ' subprop2=' + rows[i].prop3.subprop2);
}
You can view the demo here. Notice that I update newObj1.prop1 and newObj2.prop3.subprop2 to show that newObj1 and newObj2 are different instances of ComplexObj.
answered Jan 9, 2014 at 21:38
mikelt21
2,7784 gold badges26 silver badges35 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js