1 回答

TA貢獻1775條經驗 獲得超11個贊
是的,它們是等價的。ESLint 足夠聰明,可以檢測到這一點并因此提出建議。原因是您在構造中實際上只有四種選擇if/else- 當代碼不匹配前兩個條件中的任何一個時,它將始終執行外部
else {
if ($scope.followers) {
track(three);
} else {
track(four);
}
}
這只會導致兩件事之一發生。提取if ($scope.followers)aselse if遵循完全相同的邏輯路徑。
通過抽象出條件并生成真值表,然后檢查結果,可以很容易地證明這一點。它可以在紙上完成,但由于您已經有了代碼,因此也很容易將其制作為代碼:
function nested(a, b, c) {
if (a) {
return "track(one)";
} else if (b) {
return "track(two)";
} else {
if (c) {
return "track(three)";
} else {
return "track(four)";
}
}
}
function chained(a, b, c) {
if (a) {
return "track(one)";
} else if (b) {
return "track(two)";
} else if (c) {
return "track(three)";
} else {
return "track(four)";
}
}
const truthTable = [
[false, false, false],
[false, false, true ],
[false, true , false],
[false, true , true ],
[true , false, false],
[true , false, true ],
[true , true , false],
[true , true , true ],
];
for(const [a, b, c] of truthTable) {
const nestedResult = nested(a, b, c);
console.log(`called nested() with
a=${a}
b=$
c=${c}
result: ${nestedResult}`);
const chainedResult = chained(a, b, c);
console.log(`called nested() with
a=${a}
b=$
c=${c}
result: ${chainedResult}`);
console.log(`matching results?: ${nestedResult === chainedResult}`);
console.log(`------------------------`);
}
或者,您可以生成一個實際的真值表來可視化結果:
function nested(a, b, c) {
if (a) {
return "track(one)";
} else if (b) {
return "track(two)";
} else {
if (c) {
return "track(three)";
} else {
return "track(four)";
}
}
}
function chained(a, b, c) {
if (a) {
return "track(one)";
} else if (b) {
return "track(two)";
} else if (c) {
return "track(three)";
} else {
return "track(four)";
}
}
const truthTable = [
[false, false, false],
[false, false, true ],
[false, true , false],
[false, true , true ],
[true , false, false],
[true , false, true ],
[true , true , false],
[true , true , true ],
];
const enrich = truthTable
.map(row => row.concat(nested(...row), chained(...row))) //add the results of the two calls
.map(row => row.concat(row[row.length-1] === row[row.length-2])) //compare the last two
const table = document.querySelector("table");
for (const rowData of enrich) {
const newRow = table.insertRow(-1);
for (const rowValue of rowData) {
const cell = newRow.insertCell(-1);
cell.textContent = rowValue;
}
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
<table>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
<th>nested result</th>
<th>chained result</th>
<th>results equal</th>
</tr>
</table>
添加回答
舉報