2015-10-09 1 views
1

В этом коде у меня есть корзина с объектами альбома в массиве cart.items. Есть пять разных элементов альбома, но их несколько. Я пытаюсь отобразить имя альбома, исполнителя, количество приобретенного вами конкретного альбома и промежуточный итог для каждого альбома. Я не понимаю логики о том, как получить нужную информацию из массива cart.items. Вот кодКак работать с массивом, который имеет одни и те же элементы несколько раз

/** Program Description: This program simulates purchases using a 
* loop. The program creates two classes; an album class, and 
* a cart class. The initial amount of money is $1000.00. The program 
* iterates through all the albums and purchases each one, as 
* long as there is money left. Every time an album gets purchased 
* the initial amount of money is decremented by the purchase 
* price. Each time an item is purchased, it gets added to the cart. 
* The program then displays all the items purchased in the cart. 
* It should show the album name, artist name, quantity purchased, 
* and sub total for each. It then shows the total purchase price, 
* and the amount of money left over 
* 
* Pseudocode: 
* 
*  Create a constructor for Album object 
*  Create classes that inherit from Album 
*   Store these classes in an array 
*  Create a constructor for Cart object 
*  Create a const variable for initial money 
*  Loop to simulate purchases 
*   Iterate over an array of albums 
*   Purchase each one as long as there is money left 
*   Decrement money by purchase price 
*   Add item to cart 
*  Display info             **/ 

// Create a constructor for Album class 
function Album(title, artist, price){ 
    this.title = title; 
    this.artist = artist; 
    this.price = price; 
    this.date = new Date(); 
    this.quantity = Math.floor((Math.random() * 10) + 1); 
}; 
Album.prototype.purchase = function(){ 
    this.quantity--; 
    if (this.quantity > 0){ 
     return 1; 
    } 
    else{ 
     return -1; 
    } 
}; 
// Create objects that inherit from Album 
var pimpAButterfly = new Album("To Pimp a Butterfly", "Kendrick Lamar", 29.99); 
pimpAButterfly.tracklisting = ["Wesleys Theory", "For Free", "King Kunta", "Institutionalized", "These Walls"]; 

var blameItAll = new Album("Blame It All On My Roots", "Garth Brooks", 29.98); 
blameItAll.tracklisting = ["Blame It All On My Roots", "Neon Moon", "Papa", "Thunder Rolls"]; 

var killLights = new Album("Kill the Lights", "Luke Bryan", 20.83); 
killLights.tracklisting = ["Kick the Dust Up", "Kill the Lights", "Strip it Down", "Home Alone Tonight"]; 

var platinum = new Album("Platinum", "Miranda Lambert", 20.61); 
platinum.tracklisting = ["Girls", "Platinum", "Little Red Wagon", "Priscilla", "Automatic"]; 

var painKiller = new Album("PainKiller", "Little Big Town", 24.99); 
painKiller.tracklisting = ["Quit Breaking Up With Me", "Day Drinking", "Tumble and Fall", "Painkiller"]; 

// Store these objects in an array 
var albums = [pimpAButterfly, blameItAll, killLights, platinum, painKiller]; 
// Create a constructor for Cart class 
function Cart(val){ 
    this.items = []; 
}; 

Cart.prototype.add = function(val){ 
    this.items.push(val); 
}; 

Cart.prototype.remove = function(val){ 
    this.items.splice(albums.indexOf(val), 1); 
}; 

//Create a constant variable for initial money 
var INITIAL_MONEY = 1000.00; 

// Create an instance of the Cart object 
var cart = new Cart(); 

// Calculate cheapest album price 
var cheapestPrice = albums[0].price; 
for (var j = 1; j < albums.length; j++) 
    if (albums[j] < cheapestPrice){ 
     cheapestPrice = albums[j]; 
    }; 

// Loop to simulate purchases 
var i = 0; 
while(INITIAL_MONEY >= cheapestPrice){ 
    i = 0; 
    while(i < albums.length){ 
     //Purchase each one as long as there is money left 
     if (INITIAL_MONEY >= cheapestPrice){ 
      albums[i].purchase(); 
      //Decrement money by purchase price 
      INITIAL_MONEY = INITIAL_MONEY - albums[i].price; 
      //Add item to cart 
      cart.add(albums[i]); 
     } 
     i++; 
    } 
}; 


console.log(cart.items); 
/**console.log("Album Name\tArtist Name\tQuantity\tSubtotal"); 
for(var count = 0; count < cart.items.length; count++)**/ 

ответ

0

Петля через корзину и суммировать информацию вам нужно, вот некоторые псевдокод:

for(var count = 0; count < cart.items.length; count++){ 
    var item = cart.items[count]; 
    //item is now an album, now sum up the quantities into a results array, pseudocode: 
    results[item] += item.quantity 
} 

//loop through your results and display all information: 

for(var count = 0; count < results.length; count++){ 
console.log("Album: "+results[count].title); 
console.log("Artist: "+results[count].artist); 
console.log("Quantity: "+results[count].quantity); 
console.log("Subtotal: "+results[count].price * results[count].quantity); 
} 

редактировать: Это будет учитываться альбомы в корзине:

var counts = {}; 
cart.items.forEach(function(x) { counts[x.title] = (counts[x.title] || 0)+1; }); 
console.log(counts); 
+0

Позвольте мне попробовать. Разве я не должен объявлять результаты [item]? –

+0

items.quantity представляет, сколько было в магазине, чтобы купить, а не сколько их было куплено. Как узнать, сколько из тех же элементов в массиве получает количество? –

+0

см. Мое редактирование о том, как подсчитывать элементы массива – Hokascha