繁体   English   中英

JavaScript:无法将字符串与数字进行比较

[英]Javascript: unable to compare string with number

我从div获取值,并试图与if条件进行比较,但每次都以错误的方式执行,为什么? 请帮我

例子:我的代码我得到的totalcount值是2,但是同样它进入了if块,它不应该进入

我的代码:

var totalcount=$("#itemLocationGrid").jqGrid('getGridParam', 'records');//gives value 2
 Number(totalcount);

 if(totalcount===0);
   {  //every time it executes. why?
    alert("No item locations found to perform this ADD action."); 
    return false;
   }

是分号...

if(totalcount===parseInt(0)  || totalcount == "0" || totalcount == 0);
// ...here ----------------------------------------------------------^

该分号终止if语句; 紧随其后的是一个if为条件的块。 您要删除它,以便该块与if关联。


如果要在totalcount使用数字,并且jqGrid将值作为字符串返回(我不知道,但是如果需要),尤其是您想要一个整数(“整数”),请按照以下方法进行操作:

var totalcount = parseInt($("#itemLocationGrid").jqGrid('getGridParam', 'records'), 10);
// Parse it -----^ and use a radix (number base) ---------------------------------^^^^

完成此操作(或者如果jqGrid给您一个字符串),这就是您进行比较的方式:

if (totalcount === 0)
{
    // Do something because it's zero
}

使用==也可以。 不同之处在于===不会强制类型匹配,而==可以(例如, "0" == 0为true,但"0" === 0为false)。

您需要删除if条件的分号。 您也不需要使用数字。 获取记录时,您获得的totalcount已经是整数格式( 请参阅此 )。代码将如下所示。

var totalcount=$("#itemLocationGrid").jqGrid('getGridParam', 'records');//gives value 2
if(totalcount===0)
  {  //every time it executes. why?
   alert("No item locations found to perform this ADD action."); 
   return false;
 } 

尝试这个:

不需要其他条件

 if(totalcount===parseInt(0)  || totalcount == "0" ||)

您的代码:

if(totalcount == 0)// also remove ; here
       { 
        alert("No item locations found to perform this ADD action."); 
        return false;
       }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM