优化一下这段代码if (res == null || res == "undefined" || res == "") { var timer1 = setTimeout(function () { errored( (ocrRes = { text: "链接服务器异常,请检查网络!", res: isEquals, }) ); }, 300); collectionTimer.push(timer1); } else { var result = JSON.parse(res); if (result == null || typeof result == "undefined" || result == "") { custom_toast("服务器连接失败,请稍后再次尝试"); } else if (result.errCode == "0") { var results = result.result; var returnText = ""; for (var i = 0; i < results.length; i++) { if (results[i] == "0") { if (hitString == returnText) { isEquals = true; break; } returnText = ""; } else { var charValue = String.fromCharCode(results[i]); returnText += charValue; } } if (result.errCode == 0 && isEquals) { var timer3 = setTimeout(function () { resolve( (ocrRes = { text: result.errCode, res: isEquals, }) ); }, 300); collectionTimer.push(timer3); } else { var timer2 = setTimeout(function () { errored( (ocrRes = { text: "-1", res: isEquals, }) ); }, 300); collectionTimer.push(timer2); } } else { var timerNum = setTimeout(function () { errored( (ocrRes = { text: result.errCode, res: isEquals, }) ); }, 300); collectionTimer.push(timerNum); } }
时间: 2024-03-08 18:51:27 浏览: 51
可以优化代码,将重复的条件判断语句合并,并且使用严格相等(===)来进行比较,同时将setTimeout函数提取出来,避免重复代码。优化后的代码如下:
```
if (!res) {
var timer1 = setTimeout(function () {
errored((ocrRes = { text: "链接服务器异常,请检查网络!", res: isEquals }));
}, 300);
collectionTimer.push(timer1);
} else {
var result = JSON.parse(res);
if (!result) {
custom_toast("服务器连接失败,请稍后再次尝试");
} else if (result.errCode === "0") {
var results = result.result;
var returnText = "";
for (var i = 0; i < results.length; i++) {
if (results[i] === "0") {
if (hitString === returnText) {
isEquals = true;
break;
}
returnText = "";
} else {
var charValue = String.fromCharCode(results[i]);
returnText += charValue;
}
}
var timer;
if (result.errCode === 0 && isEquals) {
timer = setTimeout(function () {
resolve((ocrRes = { text: result.errCode, res: isEquals }));
}, 300);
} else {
timer = setTimeout(function () {
errored((ocrRes = { text: "-1", res: isEquals }));
}, 300);
}
collectionTimer.push(timer);
} else {
var timerNum = setTimeout(function () {
errored((ocrRes = { text: result.errCode, res: isEquals }));
}, 300);
collectionTimer.push(timerNum);
}
}
```
优化后的代码可读性更好,同时也更加简洁,避免了重复的代码。
阅读全文