javascript - isNaN() javascript,带 2 个逗号的数字

标签 javascript random numbers setinterval percentage

我正在处理百分比和 setInterval()所以我有一个

    var intervalId;
    function randomize(){
       var prc = $("#prc").val();
       var c = 0 ;
       if (!intervalId){
          intervalId = setInterval(function(){
              c = c + 1;
              var attempt = Math.random() * 100;
              if (attempt <= prc){
                  clearInterval(intervalId);
                  intervalId = false;
                  $("#attemptnbr").val(c);
              }
          }, 100);
       }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Percentage : <input type="text" id="prc"/>
<button onclick="randomize()">GO</button>
Number of attempts :<input type="text" id="attemptnbr"/>

但实际上如果用户设置 #prc输入 50.345.34 , attempt <= prc条件总是返回 true . 我试过 console.log(isNaN(prc))当此输入设置为类似 50.345.34 的数字时它总是返回 false .

为什么它被认为是一个数值?

最佳答案

But actually if the user set the #prc input to 50.345.34, the attempt <= prc condition always returns true.

很确定这是观察错误。你的prc是一个字符串,然后将由 <= 隐式转换为数字运算符(operator)。号码将为 NaN因为“50.345.34”不能被隐式转换,关系使用NaN永远不会是真的。

然而,它并没有真正改变你想做的事情,即转换 prc到一个数字故意并测试结果:

var intervalId;
function randomize(){
   var prc = +$("#prc").val();
   //        ^------------------- Note the +, that converts it to a number
   if (isNaN(prc)) {
       // Handle the invalid input
       return;
   }
   var c = 0 ;
   if (!intervalId){
      intervalId = setInterval(function(){
          c = c + 1;
          var attempt = Math.random() * 100;
          if (attempt <= prc){
              clearInterval(intervalId);
              intervalId = false;
              console.log(attempt);
          }
      }, 100);
   }
}

我应该注意,如果输入,上面的代码可能会做一些你不想要的事情:它将使用值 0 ,因为 +""0 .如果您不想这样,您可以这样做:

var prcString = $.trim($("#prc").val());
var prc = +prcString;
if (!prcString) {
    // Handle the fact they didn't enter anything
    return;
}
if (isNaN(prc)) {
    // Handle the invalid input
    return;
}

关于javascript - isNaN() javascript,带 2 个逗号的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32712513/

相关文章:

Python:定义数字列表的方差

f# - 如何编写通用数字的函数?

javascript - 数字数组排序错误

javascript - 延迟重定向 (Javascript)

GLSL 的随机/噪声函数

python - 尝试转换列表或删除列表数字周围的引号

language-agnostic - 从逻辑分布中生成样本

javascript - 如何通过函数更新全局变量

javascript - 一组输入和一个文本区域至少需要一个值

javascript - 为什么即使输入数字是 Javascript 中的字符串,年龄计算器也能正常工作?