在foreach循环闭合内中断开关 [英] breaking out of a switch within a foreach loop closure
问题描述
我有以下代码
void onSelectionChangedFiredSources( Event event, var detail,
SelectCheckboxMenuComponent target)
{
// getItemModels returns a list of objects
getItemModels( target.selectedItems )
..forEach( (item)
{
switch( item.label )
{
case 'Ear':
toggleDialog( 'paper-dialog-transition-center',
$['ear-side-dialog']);
break;
case 'Eye':
toggleDialog( 'paper-dialog-transition-center',
$['eye-side-dialog']);
break;
case 'Nostril':
toggleDialog( 'paper-dialog-transition-center',
$['nostril-side-dialog']);
break;
case 'Thorax':
toggleDialog( 'paper-dialog-transition-center',
$['thorax-side-dialog']);
break;
default:
srcDataMap.add( item.label, item.selected);
}
});
}
触发案例时,我想跳出foreach循环.
When a case is triggered, I would like to break out of the foreach loop.
请注意,每次选择更改时,所有选择均由target.selectedItems表达式返回.因此,如果首先选择"Ear",则执行循环,然后选择"Eye"时,列表返回将同时包含"Ear"和"Eye".如何做到最好?谢谢
Note that each time the selection changes, all selections are return by the target.selectedItems expression. So if 'Ear' is the first selection, the loop is executed and when 'Eye' is then selected the list return will have both Ear and Eye. How is this best done? Thanks
推荐答案
您不能中断 forEach
调用.
您不能使用 break
,因为它不是循环.这是一个函数调用,而break仅在当前函数内部起作用.
You can't use break
because it's not a loop. It's a function call, and break only works inside the current function.
您不能返回
,因为那只会继续下一个元素.
You can't return
, because that just continues with the next element.
您可以 扔
结束 forEach
,但这并不漂亮.
You can throw
to end the forEach
, but that's hardly pretty.
相反,您可以做的是根本不使用 forEach
,而是使用 for-in
循环,然后使用以下方法 break
标记为中断:
What you can do instead is to not use forEach
at all, and use a for-in
loop instead, and then break
out of that using a labeled break:
void onSelectionChangedFiredSources(Event event, var detail,
SelectCheckboxMenuComponent target) {
// getItemModels returns a list of objects
var models = getItemModels(target.selectedItems);
loop: for (var item in models) {
switch (item.label) {
case 'Ear':
case 'Eye':
case 'Nostril':
case 'Thorax':
toggleDialog('paper-dialog-transition-center',
$['${item.label.toLowerCase()}-side-dialog']);
break loop;
default:
srcDataMap.add( item.label, item.selected);
}
}
}
您需要使用带标签的 break
,因为没有标签只会破坏 switch
语句.
You need to use a labeled break
because without a label it would only be breaking the switch
statement.
这篇关于在foreach循环闭合内中断开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!