简体   繁体   中英

Multi-dimensional array and objects with properties

I'm very new in Javascript and just started to learn objects and arrays. I got very confused trying to build a two-dimensional array of products. The first array consists of categories. Each category is an array of products. Each product is an instance of the product object. Like

for car: Honda, Toyota, Ford, etc.
a Honda can consist of :

Civic, 1997, VIN#123435678, 30000 miles, good condition, $12000, etc.
Accord, 1990, VIN#203948574, 100000 miles, good and running, $1000, etc.
So an instance of a car can be a Honda. And Honda can be an array of Accord, Civic, etc

What I create is:

var salsa1 = new Product("Salsa", "Victor Manuelle", "2013", "17.00");
      var salsa2 = new Product("Salsa", "Grupo Niche", "2012", "15.00");
      var salsa = new Array();
      salsa.push(salsa1);
      salsa.push(salsa2);

      var bachata1 = new Product("Bachata", "Romeo Santos", "2011", "15.00");
      var bachata2 = new Product("Bachata", "Joan Soriano", "2013", "18.50");
      var bachata = new Array();
      bachata.push(bachata1);
      bachata.push(bachata2);

      var products = new Array();
      var count = products.push(salsa);
      count = products.push(bachata);

      document.write("<table border='0'><tr><th>Type of Music</th><th>Artist Name</th><th>Year of release</th><th>Price for CD</th></tr>");
      for (var i=0; i<count; i++)
      {
        document.write("<tr>");
        document.write("<td>" + products[i][0].type + "</td>");
        for (var j=0; j<products[i].length; j++)
        {
            products[i][j].showProduct();
            document.write("</tr><td></td>");
        }

      };

But this way is not right. Please, give me some suggestions on how to get to the right way of solution!

You can use javascript object as associative array.

var products = {cars: [], musics: []};
products.cars.push({name: 'Something', year: 2005, ...});
products.musics.push({title: 'Something', artist: 'Someone', ...});
for (var key in products) {
    if (products.hasOwnProperty(key)) { //remove any inherited property
        var items = products[key];
        // do something
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM