javascript 标签
No matter how long you've been a JavaScript developer, there will always be language features that you didn't know about until you saw them in a fringe piece of code. Your reaction generally is a bit like:
不管您是一名JavaScript开发人员已有多久了,总会有一些您不了解的语言功能,直到您在一段附带的代码中看到它们为止。 您的React通常有点像:
One of those features I see developers quizically trying to figure out is JavaScript labels, which allow you to manage break
and continue
with JavaScript loops. Let's have a look at them!
我看到开发人员奇怪地想找出的功能之一就是JavaScript标签,它允许您管理break
并continue
执行JavaScript循环。 让我们看看他们!
The basic format of a loop is {loopname}:
before the loop starts:
循环的基本格式为{loopname}:
循环开始前:
{loopName}:for({iterating}) { {actions}}
The power of labels comes with nested loops -- you can use break
and continue
, paired with the label name, to manage loop escaping:
标签的功能带有嵌套循环-您可以使用break
和continue
(与标签名称配对)来管理循环转义:
function gogogo() { firstLoop: for (let outer = 0; outer < 4; outer++) { secondLoop: for (let inner = 0; inner < 5; inner++) { if (inner === 3) { // Use continue to avoid runs 4 and 5 continue firstLoop; } console.warn(`outer: ${outer}; inner: ${inner}`); } }}/*outer: 0; inner: 0outer: 0; inner: 1outer: 0; inner: 2outer: 1; inner: 0outer: 1; inner: 1outer: 1; inner: 2outer: 2; inner: 0outer: 2; inner: 1outer: 2; inner: 2outer: 3; inner: 0outer: 3; inner: 1outer: 3; inner: 2*/
Nested loops can be difficult to manage but labels make directing and escaping them easy. The next time you want to look like a smart one in the room, break out the JavaScript labels!
嵌套循环可能很难管理,但是标签使定向和转义变得容易。 下次您想在房间里看起来像个聪明人时,突破JavaScript标签!
翻译自:
javascript 标签