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

前端 未结 4 1251
情深已故
情深已故 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:36

    You could do the following, with Array#find:

    function addToCart(pizza, size)
    {
        // find the first item where the condition is true, 
        // or undefined if there is none
        var sameSizeItem = Cart.find(function (item) {
            return pizzaAndSizeAreTheSame(item, pizza, size);
        });
    
        if (sameSizeItem) {
            sameSizeItem.quantity++;
            updateCart();
            return;
        }
    
        Cart.push({
            pizza: pizza,
            size: size,
            quantity: 1
        });
    
        updateCart();
    }
    

    A little more adjustment and you can avoid having updateCart() in two different places:

    function addToCart(pizza, size)
    {
        // find the first item where the condition is true, 
        // or undefined if there is none
        var sameSizeItem = Cart.find(function (item) {
            return pizzaAndSizeAreTheSame(item, pizza, size);
        });
    
        if (sameSizeItem) {
            sameSizeItem.quantity++;
        } else {
            Cart.push({
                pizza: pizza,
                size: size,
                quantity: 1
            });
        }
    
        updateCart();
    }
    

    If the environment(s) you're targeting do not all support Array#find, you can get a polyfill from MDN.

提交回复
热议问题