[英]Getting NaN if variable has null value
在这里,我正在通过ajax和json获得记录。 如果变量具有值,我将获得价值。 但是,如果变量“ performance”具有空值,则显示NaN
。 而不是NaN
,我想打印数字值,例如00.00
。
那可能吗? 如果是,那怎么办? 谢谢。
我的代码
function emp_month_perf(){
jQuery.ajax({
url: "<?php echo base_url(); ?>grade_tasks/emp_monthly_performance",
data:'',
type:"GET",
dataType: "json",
success:function(data){
var total_month_earn = data.total_earn_point;
var total_month_point = data.total_point;
var performance;
var per_color;
//var radius = "20px";
//alert(total_point);
performance = (((total_month_earn)/(total_month_point))*100).toFixed(2);
if(performance>80)
{
per_color = "#33CF53";
}
else if(performance>=60 && performance<=80)
{
per_color = "#E0C533";
}
else
{
per_color = "#E12827";
}
//document.getElementById("monthperformance").style.borderRadius = radius;
document.getElementById("monthperformance").style.backgroundColor = per_color;
$('#monthperformance').html(performance);
},
error:function (){}
});
}
setInterval(emp_month_perf, 300000);
使用“或”运算符将数字设置为零。
var total_month_earn = data.total_earn_point || 0;
var total_month_point = data.total_point || 0;
但是现在您可以将1/0设为无穷大。 :)
另一种选择是检查NaN,然后将该值设置为零。
var performance = (((total_month_earn)/(total_month_point))*100);
var formatted = isNaN(performance) ? "00.00" : performance.toString(2);
修复如下
performance = (((total_month_earn)/(total_month_point))*100).toFixed(2);
用
try {
performance = (((total_month_earn)/(total_month_point))*100).toFixed(2);
performance=isNaN(performance) ? "00.00" : performance;
}
catch(err) {
performance="00.00";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.