JavaScript标记的语句

JavaScript has a relatively unknown functionality which allows you to label statements.

JavaScript具有一个相对未知的功能,该功能允许您标记语句。

I’ve recently saw this feature used in Svelte to power reactive declarations, which are re-computed whenever the variables declared into the statement change:

我最近看到Svelte中使用了此功能来增强React式声明,只要声明中声明的变量发生更改,就会重新计算该声明:

$: console.log(variable)

They also allow to use a statement block, another feature of JavaScript that lets you define a block whenever you can define a statement:

它们还允许使用语句块 ,这是JavaScript的另一功能,可让您在定义语句时定义块:

$: {
  console.log(variable)
  console.log('another thing')
  //...
}

This may look strange, but it’s correct JavaScript. This statement block is assigned to the $ label.

这可能看起来很奇怪,但是它是正确JavaScript。 该语句块分配给$ 标签

The Svelte compiler internally will use this to power reactive declarations.

Svelte编译器内部将使用它来增强React式声明。

I never used this feature anywhere else, yet, but the primary use case is breaking out of a statement that is not the nearest enclosing loop or switch.

我从未在其他任何地方使用过此功能,但是主要用例是突破了不是最近的封闭循环或开关的语句。

Here’s a simple example to explain what I mean.

这是一个简单的例子来解释我的意思。

Calling break in any of those points breaks out of the switch, to avoid running the other cases:

在这些点中的任何一个上调用break都会脱离该开关,以避免运行其他情况:

for (let y = 0; y < 3; y++) {
  switch (y) {
    case 0:
      console.log(0)
      break
    case 1:
      console.log(1)
      break
    case 2:
      console.log(2)
      break
  }
}

This will print 0 1 2 to the console, as expected.

按预期,这会将0 1 2打印到控制台。

But what if we want to break out of for when we reach case 1? Here is how:

但是,如果我们想在case 1突围而出, for怎么办? 方法如下:

loop: for (let y = 0; y < 3; y++) {
  switch (y) {
    case 0:
      console.log(0)
      break
    case 1:
      console.log(1)
      break loop
    case 2:
      console.log(2)
      break
  }
}

This will print 0 1 to the console.

这会将0 1打印到控制台。

翻译自: https://flaviocopes.com/javascript-labeled-statements/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值