2013-12-11 62 views
0

我在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

如果您構建單個HTML字符串並一次寫入(即單個'document.write'調用),則它更高效(並且更容易使用HTML引擎),否則它必須處理無效的HTML一路上。一個表**必須有一個結束標記(它們可以省略TR和TD)。一個開放的TD標籤不能立即跟隨一個關閉的TR標籤,它必須跟隨一個開放的TR。 – RobG

回答

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 
    } 
} 
相關問題