无法弄清楚如何迭代循环

时间:2015-10-09 01:15:46

标签: javascript

我正在编写一个像购物车一样的程序。我将制作5个继承自Album类的专辑对象。 “专辑”类为专辑的数量生成一个随机数。我也应该创建一个Cart类。我的初始金额是1,000美元。我要编写一个循环,遍历我的一系列专辑并购买每一张专辑,直到我没有足够的钱或没有更多的特定专辑。当我遍历专辑时;如果我有足够的钱并且专辑可用,那么我购买它,扣除钱,并将其添加到购物车中。我的循环真的很难过。任何建议,将不胜感激。就像现在一样,我的循环只是遍历了专辑阵列一次,这让我留下了大约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");

1 个答案:

答案 0 :(得分:0)

就像您在问题中描述的那样,您需要统一填充购物车的相册。像这样,直到你的钱正式消失,你将逐个添加相册(按照你将它们添加到专辑列表的顺序)。

    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&gt; cheapest_album_price)。 我们需要先找到最低价格,这是由这个lil脚本完成的。

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将包含保证的最低价格