+ 1

Can you make an array of objects in JavaScript?

I'm trying to learn JavaScript, however, I'm having trouble with the rules and syntax of objects. How can you make an array of objects in JavaScript? I've tried first making an object like so: function myObject(name, value) { this.name = name; this.value = value; } And then I try to make an array of objects like so: var myObj = new myObject("Tim", 7); var myObjArr = new Array(); myObjArr[0] = myObj; Why won't this work? Thank you in advance for your help!

19th Dec 2017, 4:50 AM
bornToCode()
bornToCode() - avatar
2 Answers
+ 3
It works https://code.sololearn.com/WtBlkpWjf09L/?ref=app A better way is use push function to add objects into an array function myObject(name, value) { this.name = name; this.value = value; } var myObj = new myObject("Tim", 7); var myObjArr = new Array(); myObjArr.push(myObj); alert(myObjArr[0].name); alert(myObjArr[0].value); https://code.sololearn.com/WA79Q77JHf3r/?ref=app
19th Dec 2017, 5:17 AM
CalviÕ²
CalviÕ² - avatar
+ 2
I see, that is more dynamic. I'm not sure what I was doing wrong seeing as how your test example worked. I'll keep working at it, thank you!
19th Dec 2017, 5:56 AM
bornToCode()
bornToCode() - avatar