简体   繁体   中英

How can I make this javascript code shorter?

I have this code and I am just starting to learn javascript. I was thinking if there is anyway to make this specific code shorter?

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div id="result"></div>
        <script>
            var name = prompt("What is your name?");
            var points = prompt("What were your last test points in Web Client programming?"); 
            if (points<60) {
                document.getElementById("result").innerHTML="Hi "+name+"! You got an: F";
            } else if (points>=60 && points<=69) {
                document.getElementById("result").innerHTML="Hi "+name+"! You got an: D"; 
            } else if (points>=70 && points<=79) {
                document.getElementById("result").innerHTML="Hi "+name+"! You got an: C"; 
            } else if (points>=80 && points<=89) {
                document.getElementById("result").innerHTML="Hi "+name+"! You got an: B"; 
            } else if (points>=90 && points<=100) {
                document.getElementById("result").innerHTML="Hi "+name+"! You got an: A"; 
            } else {
                alert("Not a valid input!");
            }
        </script>
    </body>
</html>

An object indexed by grade, whose values are the threshold for that grade, will allow concise iteration through the entries to find the first one for which the user's grade reaches the lower threshold:

 var name = prompt("What is your name?"); var points = Number(prompt("What were your last test points in Web Client programming?")); const thresholds = { A: 90, B: 80, C: 70, D: 60, F: 0, }; const threshold = Object.entries(thresholds).find(entry => points >= entry[1]); document.getElementById("result").innerHTML = "Hi " + name + ": You got an; " + threshold[0];
 <div id="result"></div>

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