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

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

    function addToCart(pizza, size) {
        var res = Cart.some(function(cartItem)) {
            if(pizzaAndSizeAreTheSame(cartItem, pizza, size)) {
                cartItem.quantity++;
                updateCart();
                //Want go out from addToCart if this return is reached
                return true;
            }
            return false;
        });
    
        if(res) {
          return;
        }
        //Don`t want the code run after return;
        Cart.push({
            pizza: pizza,
            size: size,
            quantity: 1
        });
        updateCart();
    }
    

提交回复
热议问题