javascript - 如果变量具有空值则获取 NaN

标签 javascript json ajax nan

在这里,我通过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/

相关文章:

php - Perl 正则表达式模式在 php 中有效,但在 javascript 中无效?

c# - 如何从嵌套的 JObject 中获取特定属性的值

json - 从传入的 JSON 反序列化 LocalDateTime

ajax - jqueryui 对话框在 ajax 调用完成之前不会打开(仅限 IE)

javascript - 仅使用 javascript 在文本框中写入预定义的文本

javascript - 在 HTML 基础上创建 JSON,反之亦然

javascript - 在 javascript 函数中恢复 href 属性?

javascript - 处理格式不固定的 JSON 数据

javascript - 如何更新要点?

javascript - 使用 javascript 或 ajax 弹出窗口显示所选选项