Home » Javascript » javascript – Running a for loop and a switch case at the same time

javascript – Running a for loop and a switch case at the same time

Posted by: admin February 23, 2020 Leave a comment

Questions:

So I have an array of dice, and I want to add a className on the percentage of betting a score using javascript and/or jquery.

So I was thinking of using a for loop and a switch case.

The problem I have, it wont go through the whole array, Im guessing I need another for loop inside with the switch case. I just can’t seem to get it to work…

let diceArray = [4, 6, 8, 12, 20];
let diceRolled = 10;

function percentage() {
    for (var i = diceArray.length - 1; i >= 0; --i) {
    //weird code
    let abc = diceArray[i] - diceRolled;
    let def = 100 / diceArray[i];
    let hig = def * abc;
    let code = hig.toFixed(0);

    for (var j = diceArray.length - 1; j >= 0; --j) {
     switch (true) {
                    case code >= 80:
                        return console.log(diceArray[i] + "a");
                        break;
                    case code >= 60 && code <= 79:
                        return console.log(diceArray[i] + "b");
                        break;
                    case code >= 40 && code <= 59:
                        return console.log(diceArray[i] + "c");
                        break;
                    case code >= 39:
                        return console.log(diceArray[i] + "d");
                        break;
                    default:
                        return console.log(diceArray[i] + "e");               
    }
};

Ideally I would like it to return

20 "a"
12 "c"
ect ect
How to&Answers: