从调用了forEach()数组方法的方法返回.的JavaScript [英] Return from a method in which forEach() array method was called. JavaScript
问题描述
我正在使用从JavaScript中的数组调用的forEach()方法.当我在为数组中每个元素调用的方法内部写入return;
时,我从为特定元素调用的方法中退出,仅此而已.但是我真正想要的是从名为forEach()的数组的方法中退出.这是代码:
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 out from the method which was called for a specific element and that is all. But what I actually want is to return out from the method in which array called forEach(). Here is the code:
function addToCart(pizza, size)
{
Cart.forEach(function(cartItem)
{
if(pizzaAndSizeAreTheSame(cartItem, pizza, size))
{
cartItem.quantity++;
updateCart();
//Want go out from addToCart if this return is reached
return;
}
});
//Don`t want the code run after return;
Cart.push
({
pizza: pizza,
size: size,
quantity: 1
});
updateCart();
}
这是到目前为止我提出的解决方案:
Here is solution with which I came up so far :
function addToCart(pizza, size)
{
var leaveTheMethod = false;
Cart.forEach(function(cartItem)
{
if(pizzaAndSizeAreTheSame(cartItem, pizza, size))
{
cartItem.quantity++;
updateCart();
leveTheMethod = true;
}
});
if(leaveTheMethod)
{return;}
//Don`t want the code run after return;
Cart.push
({
pizza: pizza,
size: size,
quantity: 1
});
updateCart();
}
我想知道是否有更好的解决方案.
I would like to know are there any better solutions to the problem.
与该问题相比:如何使Array短路. forEach喜欢打电话吗? 我对了解forEach()循环中的新方法不感兴趣,并且我不想打破forEach(),而是摆脱包含forEach()调用者方法的问题.
Compared to that question: How to short circuit Array.forEach like calling break? I am not interested in knowing the new method in forEach() loop and I want to break not from forEach() but from encompassing the forEach() caller method.
推荐答案
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();
}
这篇关于从调用了forEach()数组方法的方法返回.的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!