[英]Javascript refactoring spaghetti code of if/else
想象一個 function 返回一個具有 3 個字段的 object。
現在,我為數組中的每個元素調用 function 並解構這些字段
const array = [1, 2, 3];
for (const element of array) {
const {
field1,
field2,
field3,
} = await function(element);
...
}
我需要檢查這三個字段的值是否不包含在這個令牌數組中:
const DANGEROUS_TOKENS = ["possible", "sure"];
如果包含其中一個,我必須打破循環(忽略下一次迭代)
這就是我正在做的事情:
for (const element of array) {
const {
field1,
field2,
field3,
...,
fieldN
} = await function(element);
if (DANGEROUS_TOKENS.includes(field1)) {
handleElement();
break;
} else if(DANGEROUS_TOKENS.includes(field2)) {
handleElement();
break;
} ... the same for the next fields
}
我怎樣才能避免這個冗長的 if-else 指令?
聽起來你只需要一組屬性來迭代:
const props = ['field1', 'field2', 'field3'];
for (const element of array) {
const result = await theFunction(element);
if (props.some(prop => DANGEROUS_TOKENS.includes(result[prop]))) {
handleElement();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.