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打印到控制台。
本文深入探讨了JavaScript中鲜为人知的标签语句功能,详细介绍了如何使用此功能进行反应式声明,特别是在Svelte框架中的应用。通过实例展示了如何利用标签语句控制循环和开关的跳出,为读者提供了理解和运用这一特性的全面指南。

775

被折叠的 条评论
为什么被折叠?



