I’m sure I’m missing something trivial. This code compiles and the console.log(albums[I]); line within the loops prints each item as expected. Nothing from the console.log lines at the end (supposed to print the new value of money) seems to print. That line was printing until I added the while loop portion above, but I don’t see that it is conditional on that?
//initial value 1000
var money = 1000.00;
//while money > price, purchase next album
var i = 0;
//for each album whild index is less than albums array length, increment
//while the total quantity of albums is greater >0
var totalqty=0;
for(i=0; i < albums.length; i++){
totalqty += albums[i].Quantity;
}
while(totalqty > 0) {
for (i=0; i < albums.length; i++){
//if money is greater than the price and album has quantity to buy
if(money > albums[i].Price && albums[i].Quantity>=1){
//purchase item
albums[i].purchase();
//decrement initial money by purchase price
money -= albums[i].Price;
//move each item to the cart
mycart.add(albums[i]);
console.log(albums[i]);
}
}
}
console.log("The amount of money from the initial $1000.00 is" + ' ' + "$" + money.toFixed(2));
It may be because it’s early here and I’m so tired
But I don’t see a way for that while loop to end? Its condition is totalqty > 0, but I don’t see inside the loop where totalqty is ever changed. So if totalqty is greater than zero, it’ll just… keep looping. It’s probably never getting to your log?
You left out a few things that are vital for the script to work. One of them is the array containing the information about your albums. You also need to change the <while> conditions. I have also commented out the purchase function and the add-to-cart function as they are not present.
The following script will do it for you:
<script type="text/javascript">
//while money > price, purchase next album
//for each album while index is less than albums array length, increment
//while the total quantity of albums is greater >0
//
var albums=[{title:"album1",qty:3, price:30},{title:"album2",qty:1, price:10},{title:"album3",qty:2, price:20}];
var i=0, money=1000, totalqty=0; //initial values
//
for(i=0; i < albums.length; i++){ totalqty += albums[i].qty; }
//
while(totalqty > 0 && money >0)
{ for (i=0; i < albums.length; i++)
{ if(money > albums[i].price && albums[i].qty>=1)
{ //purchase item // albums[i].purchase();
//
money -= albums[i].price; // decrement money by purchase price
albums[i].qty--;
totalqty--;
//move each item to the cart // mycart.add(albums[i]);
console.log("totalqty= "+totalqty+" Title= "+albums[i].title+" money= "+money);
}
}
}
console.log("The amount of money left from the initial $1000.00 is" + ' ' + "$" + money.toFixed(2));
</script>