欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript 标签_JavaScript标签

程序员文章站 2022-04-29 13:43:15
...

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通常有点像:

javascript 标签_JavaScript标签

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标签,它允许您管理breakcontinue执行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:

标签的功能带有嵌套循环-您可以使用breakcontinue (与标签名称配对)来管理循环转义:


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: 0
outer: 0; inner: 1
outer: 0; inner: 2
outer: 1; inner: 0
outer: 1; inner: 1
outer: 1; inner: 2
outer: 2; inner: 0
outer: 2; inner: 1
outer: 2; inner: 2
outer: 3; inner: 0
outer: 3; inner: 1
outer: 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标签!

翻译自: https://davidwalsh.name/javascript-labels

javascript 标签