简体   繁体   中英

In the switch construction generate a lot of case statements

I have an educational task in which i have to write the function that generates 1000 case statements.

function f(x) { // function
    let y; // variable
    switch (x) { // switch
        for(let z; z < 1000; z++){ // loop
           y = case x:
               alert('True');
               break;
               return y
        }
    }
}

I don't know how to loop through case statements in the proper way

For starters I do not think what you're doing is correct. You cannot add cases to a switch. Tho maybe i'm misunderstanding who knows. but anyways,

The best way ( in my opinion ) to get 1000 cases that just do an alert would be

function f(x) { // function
    let text = `switch(x){`;
    for(let z =0;z<1000;z++){
        text+=`case ${z}:alert("true");break;`;
    }
    text+=`}`;
    eval(text);
}
f(100);//true
f(1001); //nothing

although this is quite stupid as this is quite a waste, the better way would be

function f(x){
    if(x>=0&&f<=1000) alert("true");
}

Also in the future you should try to deter from making such long for loops, those things can crash applications and browsers when running. Though now days most get along fine unless you do too many long ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM