javascript - What is correct/clean Switch (or functions in general) control flow?
问题描述
I stumbled upon a bug with my switch statement (two cases) wherein both cases ran because the former made the latter true. I found two solutions, but I don't know which one I should use or if I should combine both.
My initial thought was simply to add breaks at the end of each case. But my coworker suggested I swap the order as the latter can't interfere with the former that way. Maybe I should do both? I think breaks are clearer at a glance, but swapping them is elegant. What would you prefer to see from your coworker?
**---OPTION 1---**
var created = false;
function clicker(){
switch(created){
case false:
**some code**
created = true;
break;
case true:
**some code**
break;
}
}
**---OPTION 2---**
var created = false;
function clicker(){
switch(created){
case true:
**some code**
case false:
**some code**
created = true;
}
}
Initially, I ran option 1 but without the breaks. Case "false" would run, make case "true" = true, then case "true" would run.
Both of these options fix it. Which is better? Do you have an even better solution?
解决方案
只需使用一个if
语句:
function clicker() {
if (created) {
//Some code
} else {
//Some code
created = true;
}
}
推荐阅读
- oracle - 在 Oracle 中想将 Image BLOB 数据转换成 BMP BLOB
- amazon-s3 - AWS Glue 中的 Configparser 未从 S3 读取配置文件
- amazon-web-services - Windows Server 2016 中的端口映射 - Docker
- w3wp - 工作进程 (w3wp) 在使用 Oracle OracleDataNotify.OnNotificaton 时在 Windows 10 和服务器中崩溃
- c++ - 为什么 C++ 不按运行时类型破坏对象?
- swift - 表格视图问题中的 Swift 故事板
- java - 如何在垂直和水平方向上减慢 Recyclerview 的滚动速度?
- javascript - 从预览PHP JS中删除一些文件后如何上传多个文件
- android - 未收到 Instamojo Android SDK 付款回调
- sql-server - SQL Server:读取提交中的原子更新,可以检测并发写入吗?