在这里,我通过ajax和json获取记录。
如果变量有,我会得到值(value)。
但是,如果变量 "performance" 有空值,它显示 NaN
。
我想打印像 00.00
这样的数字值,而不是 NaN
。
这可能吗?如果是那么如何? 谢谢。
我的代码,
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);
最佳答案
使用 OR 运算符将数字设置为零。
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);
关于javascript - 如果变量具有空值则获取 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34613774/