我正在嘗試使用地圖物件實作 switch 陳述句替代方案,并且在我宣告地圖時正在呼叫應該根據條件呼叫的函式
這是我實作的簡化代碼
someMethodName(someParams, otherParams) {
const verifyThis = callExternalApi(someParams);
const customSwitch = {
oneValue: this.doThis(otherParams),
anotherValue: this.doThat(otherParams),
};
const possibleValues = ["oneValue", "anotherValue"];
if (possibleValues.includes(verifyThis))
return customSwitch[verifyThis];
return this.defaultCase(otherParams);
}
我在要呼叫的方法中放置了一個 console.log,發現它們都被呼叫了,據說是在我宣告 customSwitch 時,然后在通過 if 子句時呼叫了其中一個方法。
我該如何解決這個問題以避免呼叫我的方法?
uj5u.com熱心網友回復:
使用一個物件,它的值是函式,當被呼叫時,呼叫其他函式:
const customSwitch = {
oneValue: () => this.doThis(otherParams),
anotherValue: () => this.doThat(otherParams),
};
并在回傳時呼叫
return customSwitch[verifyThis]();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447851.html
標籤:javascript 表现 开关语句
