本文共 1848 字,大约阅读时间需要 6 分钟。
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
打印到控制台。
翻译自:
转载地址:http://ehqgb.baihongyu.com/