英文:
What is the closest equivalent to Go's switch without condition in JavaScript?
问题
在Go语言中,我可以使用一个没有条件的switch
语句,而是在case
分支中提供条件,例如:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("早上好!")
case t.Hour() < 17:
fmt.Println("下午好。")
default:
fmt.Println("晚上好。")
}
}
(摘自https://tour.golang.org/flowcontrol/11)
我喜欢这种方法的原因是它比if-else if-else if-…
更简洁。不幸的是,在JavaScript中无法使用这种结构。
我该如何使用一些(奇怪的)语言结构创建尽可能接近这种效果的东西?
英文:
In Go, I can use a switch
without a condition, and instead provide the conditions in the case
branches, such as:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
(Taken from https://tour.golang.org/flowcontrol/11)
What I like about this approach is that it is much cleaner than if-else if-else if-…
. Unfortunately, this construct is not possible in JavaScript.
How could I create something that looks like this as closely as possible, using some (weird) language constructs?
答案1
得分: 3
你可以使用与Go语言中几乎相同的结构:
var now = new Date();
switch (true) {
case now.getHours() < 12:
console.log('早上好');
break;
case now.getHours() < 17:
console.log('下午好');
break;
default:
console.log('晚上好');
}
这段代码会根据当前时间输出不同的问候语。
英文:
You can use virtually the same construct as in Go:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var now = new Date();
switch (true) {
case now.getHours() < 12:
console.log('Good morning');
break;
case now.getHours() < 17:
console.log('Good afternoon');
break;
default:
console.log('Good evening');
}
<!-- end snippet -->
答案2
得分: 1
你可以在case子句中使用条件语句。
var a = 2;
switch (true) { // 严格比较!
case a < 3:
console.log(a + ' 小于 3');
break;
}
英文:
You could use conditions at the case clause.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var a = 2;
switch (true) { // strict comparison!
case a < 3:
console.log(a + ' is smaller than 3');
break;
}
<!-- end snippet -->
答案3
得分: 1
滥用语言,
var now = new Date();
now.getHours() < 12 && console.log('早上好') ||
now.getHours() < 17 && console.log('下午好') ||
now.getHours() >= 17 && console.log('晚上好')
英文:
abusing the language,
var now = new Date();
now.getHours() < 12 && console.log('Good morning') ||
now.getHours() < 17 && console.log('Good afternoon') ||
now.getHours() >= 17 && console.log('Good evening')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论