Having trouble with 'while' loop in javascript

前端 未结 3 647
长发绾君心
长发绾君心 2021-01-28 18:55

I\'m new with javascript, and I\'m having some trouble understanding why this code doesn\'t execute:

var weight;

wight=parseInt(prompt(\"Please, enter weight\")         


        
相关标签:
3条回答
  • 2021-01-28 19:16

    spelling of weight :

    while (wight>0);
    
    while (weight>0);
    

    also in

    document.write("Tax will be" + wight*10);
    
    document.write("Tax will be" + weight*10);
    
    0 讨论(0)
  • 2021-01-28 19:24

    Try this

    var weight;
    
    weight=parseInt(prompt("Please, enter weight"));
    
    while (weight>0)
    { 
      if (weight>199 && weight<300)
    {
      document.write("Tax will be" + weight*5);
    }
      else 
    {
      document.write("Tax will be" + weight*10);
    }
    }
    
    0 讨论(0)
  • 2021-01-28 19:35
    while (wight>0);
    

    The semicolon effectively makes that loop: while wight is greater than 0, do nothing. This forces an infinite loop, which is why the rest of your code doesn't execute.

    Also, 'wight' is not the same as 'weight'. This is another error.

    Furthermore, if you change that line to while (weight > 0), you will still have an infinite loop, because the code that then executes does not alter 'weight' - thus, it will always be greater than 0 (unless a number less than 0 was entered at the prompt, in which case it won't execute at all).

    What you want is:

    var weight;
    weight=parseInt(prompt("Please, enter weight")); // Missing parenthesis
    // Those two lines can be combined:
    //var weight = parseInt(prompt("Please, enter weight"));
    
    while(weight>0)
    { 
        if (weight>199 && weight<300)// REMOVE semicolon - has same effect - 'do nothing'
        {
            document.write("Tax will be" + weight*5);
            // above string probably needs to have a space at the end:
            // "Tax will be " - to avoid be5 (word smashed together with number)
            // Same applies below
        }
        else 
        {
            document.write("Tax will be" + weight*10);
        }
    }
    

    That is syntactically correct. You still need to either change the while condition, or alter 'weight' within that loop, to avoid an infinite loop.

    0 讨论(0)
提交回复
热议问题