我是Javascript的新手,刚开始学习对象和数组。我试图构建一个二维数组的产品时非常困惑。第一个数组由类别组成。每个类别都是一系列产品。每个产品都是产品对象的一个实例。喜欢
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
我创造的是:
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>");
}
};
但这种方式不对。请给我一些关于如何找到正确解决方案的建议!
答案 0 :(得分:0)
您可以将javascript对象用作关联数组。
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
}
}