0

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
  • 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. Commented Jan 9, 2014 at 21:11

2 Answers 2

1
var rows = [];
for(var i = 0; i < 7; i++)
{        
    rows.push(new Object());
}
rows[0].name = "Hello World!";
alert(rows[0].name);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

http://jsfiddle.net/p5evg/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.