我正在编写代码来找到合适的目标并对其进行后续操作。我当前的代码将首先尝试查找类型 1。如果它不存在,我将尝试查找类型 2,依此类推。因为 find 函数消耗 CPU 太多,所以我想避免一开始就使用它来查找所有类型。以下是我当前的代码。我怎样才能简化它们?
const target1 = find1(Type1);
if(target1){
operate1(target1);
}else{
const target2 = find2(Type2);
if(target2){
operate2(target2);
}else{
const target3 = find3(Type3);
if(target3){
operate3(target3);
}else{
...
}
}
}
尝试创建一个检查列表并循环遍历它们。 这将删除嵌套,但会添加循环。
const procedures = [
procedure1,
procedure2,
procedure3,
() => {
console.log("nothing...");
},
];
for (let i = 0; i < procedures.length; i++) {
if (procedures[i]()) break; // stop if procedure is done
}
function procedure1() {
const target1 = find1(Type1);
if (target1) {
operate1(target1);
return true; // notify that procedure is done
}
}
function procedure2() {
const target2 = find2(Type2);
if (target2) {
const res = operate2(target2);
if (res === null) return false; // continue with next procedure
// notify that procedure is done
return true;
}
}
function procedure3() {
const target3 = find2(Type3);
if (target3) {
const res = operate3(target3);
return true;
}
}
创建一个具有所有参数的对象。 如果找到则循环并中断。
const targets = [
{ type: Type1, find: find1, operate: operate1 },
{ type: Type2, find: find2, operate: operate2 },
{ type: Type3, find: find3, operate: operate3 },
// Add more types as needed
];
let found = false;
for (const { type, find, operate } of targets) {
const target = find(type);
if (target) {
operate(target);
found = true;
break; // Exit loop if target is found
}
}
if (!found) {
// Handle case when no target is found
console.log("No target found");
}
您可以将此代码移至单独的函数并利用提前返回:
function findTarget()
{
const target1 = find1(Type1);
if(target1){
operate1(target1);
return;
}
const target2 = find2(Type2);
if(target2){
operate2(target2);
return;
}
const target3 = find3(Type3);
if(target3){
operate3(target3);
return;
}
...
}
或者如果你的变量/函数确实是这样命名的,请使用简单的循环:
for (let i = 1; i <= possibleTypes; i++) {
let target = window['find' + i](window['Type' + i])
if (!target) {
continue;
}
window['operate' + i](target);
break;
}