Return from a method in which forEach() array method was called. JavaScript

前端 未结 4 1249
情深已故
情深已故 2021-01-28 07:19

I am using forEach() method called from an array in JavaScript. When I write return; somewhere inside the method which is called for every element in array I return

4条回答
  •  失恋的感觉
    2021-01-28 07:40

    You could improve by making your cart an object that has methods for adding to it and a quantities property. That property would have as keys the different combinations of pizza and size, and as values the quantities for them. This would replace the array you currently have.

    Then you can access these properties directly without having to loop at all, and without the need for the function pizzaAndSizeAreTheSame.

    Here is an example of you could implement that:

    function Cart() { // Put all cart functionality in one object/constructor
        // Make the list of items in the cart an object instead of an array
        this.quantities = {}; 
    }
    
    // Define the methods on the Cart prototype
    Cart.prototype = {
        update: function() {
            // whatever logic you had in updateCart
        },
        add: function(pizza, size) {
            var key = pizza + '|' + size;
            this.quantities[key] = (this.quantities[key] || 0) + 1;
            this.update();
        },
        toArray: function() { // In case you need your original format also
            return Object.keys(this.quantities).map(function (key) {
                return {
                    quantity: this[key],
                    pizza: key.split('|')[0],
                    size: key.split('|')[1]
                };
            }.bind(this.quantities))
        }
    };
    
    // Demo: create a cart and add items to it.
    cart = new Cart();
    cart.add('Four seasons', 'medium');
    cart.add('Four seasons', 'medium');
    cart.add('Vegetarian', 'large');
    console.log(cart.toArray());
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题