问题
I'm getting on the const train and want to start avoiding let at all costs.
The problem I'm seeing is the below case - how would I use const in a situation with more than 2 forks in a logic tree?
What's the equivalent pattern with const?
function getResult(input) {
let result;
switch (input): {
case (1): { result=x;}
case (2): { result=y;}
case (3): { result=x;}
...etc
}
/*
...additional conditionals and functions depending on the outcomes
of switch statement
*/
}
thanks,
回答1:
const result = [x,y,x][input - 1];
It's an array that's accessed by index.
回答2:
There is nothing wrong with using let in this case. Const is useful for creating non changing variables throughout the file, function or class. For example, storing a non changing base url for http calls (https://your.domain.here/).
Whereas let and var are more suited to changing variables such as the amount of time a user clicks on a button, or slider to select a minimum and maximum date/age range.
However, you will want to change your switch statement to a valid statement like so:
switch (input) {
case 1: {
result=x;
break;
}
case 2: {
result=y;
break;
}
case 3: {
result=x;
break;
}
default:
break;
}
回答3:
While I don't necessarily agree with "avoiding let at all cost", I'd say the best alternative for using a switch statement is to put it in a separate function and use return.
The example below shows a pure inner result function that holds the switch logic. Instead of assigning to a variable, it returns a result as soon as it finds a match.
const getInnerResult = (x, y, input) => {
switch (input) {
case 1:
case 3: return x;
case 2: return y;
default: return null;
}
}
const getResult = function(input) {
const result = getInnerResult("a", "b", input);
// Other logic using the `result` variable
return result ? result.toUpperCase() : "-";
};
console.log(getResult(2));
console.log(getResult(5));
来源:https://stackoverflow.com/questions/48503199/how-to-use-const-when-there-are-multiple-conditions