I am trying to build an array of objects in javascript. Somehow I have not found the answer I am looking for anywhere. Yes I did search questions.
So a traditional object has properties obviously such as:
item being the object
item = new Object();
with properties and methods
item.name = "sword"; // "sword" being the string name of the object
item.buy = buy; //buy being a function to add said item
that's just great and I get that.
I get arrays too.
My question is, if I want say 20 of those objects, how could i make them in an array instead of making many objects
example, I know I can do this.
item1 = new Object();
item1.name = "sword";
item1.buy = buy;
item2 = new Object();
item2.name = "shield";
item2.buy = buy;
However, I would like to do something like this
item = new Array();
item[0].name = "sword";
item[0].buy = buy;
item[1].name = "shield";
item[1].buy = buy;
Maybe it's obvious, but I'm not getting what's wrong here.
When i attempt to call
item[0].buy();
I encounter the error "Uncaught TypeError: Object 0 has no method 'buy' " and item[0].name is undefined.
What am I doing wrong and how do I go about this?