在 JavaScript If. 中使用逻辑运算符"&&"时获取"undefined"结果。其他语句



该代码用于选择收入基于收入的联邦贫困水平( var fpl (百分比类别( var收入(。当我运行此脚本时,当我使用&& 逻辑运算符时,我的结果是"未定义的"。如果我使用 || 逻辑运算符,我会遇到错误的答案 - " 101-185%" - 无论我用什么数字用于 var Incomem 。。p>

<p id="demo"></p>
<script>
  function FPL() {   
    var income = '4200.00';
    var fs = '1';
        var fpl;  
        if(fs == '1') {
            if(income < '1022.00')
               fpl = "0-100%";  
            if (income > '1022.00' && income < '1882.00') 
               fpl = "101-185%";   
            if (result3 > '1882.00' && income < '2033.00') 
               fpl = "186%-200%";
            if (income < '2033.00')
               fpl ="'201% & Over";
            return fpl;                
        }             
        result6 = 'Federal Poverty Level: ' + fpl;
        document.getElementById("demo").innerHTML = result6;
 }   
</script>

是其他逻辑运算符。.如果在Javasscript中使用的语句使用不同?

首先,让我们检查您的代码,因为您有一些错误,我会添加有关它们在哪里的评论。

注意:在比较字符串时也要小心,例如"400" > "100000"将返回true。因此,如果您想比较值,请在比较之前对其进行解析。

  function FPL() {   
    var income = '4200.00';
    var fs = '1';
        //set a default value here to fpl or inside an else.
        var fpl;  
        if(fs == '1') {
            //on all these ifs, you dont have an else, then if your income doesnt fill your criteria, it will be undefined.
            if(income < '1022.00')
               fpl = "0-100%";  
            if (income > '1022.00' && income < '1882.00') 
               fpl = "101-185%";   
            if (result3 > '1882.00' && income < '2033.00') //result3 doesnt even exist, this will throw an error.
               fpl = "186%-200%";
            if (income < '2033.00')
               fpl ="'201% & Over";
            // if you return here, how do you expect the following code to execute? 
            // you just needed to continue the workflow
            return fpl;                
        }             
        //this code is never executed, unless fs is different than 1 (but it is hardcoded)
        result6 = 'Federal Poverty Level: ' + fpl;
        document.getElementById("demo").innerHTML = result6;
 }   

在这里您有没有错误并修复的代码。

function FPL() {
  //parse the value to get the number.
  var income = parseFloat('4200.00');
  var fs = '1';
  var fpl;
  if (fs == '1') {
    if (income < parseFloat('1022.00'))
      fpl = "0-100%";
    else if (income > parseFloat('1022.00') && income < parseFloat('1882.00'))
      fpl = "101-185%";
    else if (income > parseFloat('1882.00') && income < parseFloat('2033.00'))
      fpl = "186%-200%";
    else if (income < parseFloat('2033.00'))
      fpl = "'201% & Over";
    else
      fpl = 'default value';
  }
  result6 = 'Federal Poverty Level: ' + fpl;
  document.getElementById("demo").innerHTML = result6;
}
FPL();
<p id="demo"></p>

快速查看后,您在此行上有一个错误:

if(result3>'1882.00'

" result3"确实是不确定的,请尝试"收入"

您的 income value不属于您的任何一个if语句(我想,您想写if (income > /* instead of < */ "2033.00"),因此fpl仍然不确定

相关内容

  • 没有找到相关文章

最新更新