不知道如何通过循环进行迭代

Can't figure out how to iterate through loop

本文关键字:迭代 循环 何通过 不知道      更新时间:2023-09-26

我正在编写一个像购物车一样的程序。我要从专辑类继承5个专辑对象。Album类为专辑的数量生成一个随机数。我还应该创建一个Cart类。我的初始金额是1000美元。我要编写一个循环,遍历我的专辑数组,并购买每一张专辑,直到我没有足够的钱或没有更多的特定专辑。当我遍历专辑时;如果我有足够的钱,专辑是可用的,然后我购买它,扣除的钱,并把它添加到购物车。我的循环真的很困难。任何建议都将不胜感激。现在,我的循环只对albums数组进行了一次迭代,这就给我留下了大约800美元的剩余。很明显,这不是我想要的。我试着嵌套一个循环,但我仍然失去了逻辑。这是我的代码…

   /** 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();
    // Loop to simulate purchases
        var i = 0;
        while(INITIAL_MONEY > 0){
i = 0;

while(i < albums.length){
        //Purchase each one as long as there is money left
        if (INITIAL_MONEY >= albums[i].price){
            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 (INITIAL_MONEY);

        console.log(INITIAL_MONEY);
    //console.log("Album Name'tArtist Name'tQuantity'tSubtotal");

就像您在问题中描述的那样,您需要始终用专辑统一地填充购物车。就像这样,直到你的钱正式花光,你将一个接一个地添加专辑(按照你将它们添加到专辑列表的顺序)。

    while(INITIAL_MONEY > 0)
    {
        //don't forget to reset your counter!
        i = 0;
        while(i < albums.length)
        {
            //Purchase each one as long as there is money left
            if (INITIAL_MONEY >= albums[i].price){
                albums[i].purchase();
                //Decrement money by purchase price
                INITIAL_MONEY = INITIAL_MONEY - albums[i].price;
                //Add item to cart
                cart.add(albums[i]);
            }
            i++;
        }
    };

我看到别人已经在评论中抢在我前面了。

编辑:您的问题描述指出,每个专辑都有一定数量的可用专辑,因此您可能必须在内部while循环中添加if语句,并处理每次将专辑放入购物车时减去专辑数量的问题。

EDIT2:外部while循环将永远继续执行,除非碰巧你买的最后一张专辑把你的最后一美元变成了空气。必须将外部while循环中的谓词更改为while (INITIAL_MONEY> cheapest_album_price)。我们需要首先找到最低的价格,这是由这个小脚本完成的。

var cheapest_album_price = 999999; //is there something like int.MaxValue in javascript? Probably not.
for(var j = 0; j < albums.length; j++)
{
    if(cheapest_album_price > albums[j].price)
        cheapest_album_price = albums[j].price;
}

现在cheapest_album_price将包含保证的最低价格