我正在处理百分比和 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/