GivenPie
GivenPie

Reputation: 1489

Javascript looping error with arrays

I am trying to prompt the user for a weight smaller than 126. Then my javascript is supposed to classify the weight into a category. I have used arrays but every time I loop it writes the 3rd array, superfly class. What can I do to make it function properly?

var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
var weight = parseInt(prompt("What is your weight?"), 10);

while (weight > 126) {
    alert('Please enter a weight lighter than 126');
    weight = parseInt(prompt("What is your weight?"), 10);
}

recruit();

function recruit() {
    var weightClass = wArray[0];

    if (0 < weight && weight < 112) {
        weightClass = wArray[1];
    } else if (112 < weight && weight < 115) {
        weightClass = wArray[2];
    } else if (weight > 115 && weight < 118) {
        weightClass = wArray[3];
    } else if (weight > 118 && weight < 122) {
        weightClass = wArray[4];
    } else if (weight > 122 && weight < 126) {
        weightClass = wArray[5];
    }

    document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}

Upvotes: 0

Views: 71

Answers (2)

Jon Newmuis
Jon Newmuis

Reputation: 26502

Your first if condition is incorrect. You say if (112 < weight < 115). This first does 112 < weight, then takes the result of that and compares it to 115.

112 < weight evaluates to true or false; when used in numeric comparisons, true is 1 and false is 0. (Obviously) both 1 and 0 will always be less than 115, so this condition will always be true.


Also note that this script should be run onload of the page. This is because the div with the ID weight may not have loaded when the script executes and attempts to populate it. You can do this by saying:

<script type="text/javascript">
    var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];

    function calculateWeight() {
        var weight = parseInt(prompt("What is your weight?"), 10);

        while (weight > 126) {
            alert('Please enter a weight lighter than 126');
            weight = parseInt(prompt("What is your weight?"), 10);
        }

        recruit();
    }

    function recruit() {
        var weightClass = wArray[0];

        if (weight >= 112 && weight < 115) {
            weightClass = wArray[1];
        } else if (weight >= 115 && weight < 118) {
            weightClass = wArray[2];
        } else if (weight >= 118 && weight < 122) {
            weightClass = wArray[3];
        } else if (weight >= 122 && weight < 126) {
            weightClass = wArray[4];
        }

        document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');

    }
</script>
<body onload="calculateWeight()">
    <!-- include body contents here -->
</body>

Upvotes: 2

Recognizer
Recognizer

Reputation: 756

the line:

if (112 < weight < 115) {

Should be

if (112 < weight && weight < 115) {

Upvotes: 1

Related Questions