Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - How to use CONST when there are multiple conditions

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...