如何阻止NaN显示在结果中?

时间:2012-03-17 09:05:37

标签: jquery nan

我有这个jquery脚本

 $(document).ready(function() {
   $(function(){
    $("#result").submit(function(e) {
       e.preventDefault();
       var ele = $("#element").val(),
        target = $("#target").val(),
        context = $("#context").val(),
        border = $("#border").val(),
        margin = $("#margin").val(),
        padding = $("#padding").val();

    console.log(ele, target, context, border, margin, padding);

    var DoubleMargin = parseInt(margin, 10) * 2;
    var DoublePadding = parseInt(padding, 10) * 2;
    var DoubleBorder = parseInt(border, 10) * 2;


    var ActualTarget = parseInt(target, 10) - parseInt(DoubleBorder, 10) - parseInt(DoubleMargin, 10) - parseInt(DoublePadding, 10) * 1;
    var result3 = parseInt(target, 10) - parseInt(DoubleMargin, 10) * 1;
    var MarginResult = parseInt(margin, 10) / parseInt(target, 10) * 100;
    var PaddingResult = parseInt(padding, 10) / parseInt(target, 10) * 100;
    var OriginalResult = parseInt(ActualTarget, 10) / parseInt(context, 10) * 100;
    var BorderResult = parseInt(target, 10) - parseInt(border, 10) * 1;

    //$(".result").append(ele + " " + result + "%");
    $("<p></p>", {
        html: ele + " {<br><span>width: " + OriginalResult + "%;" + " /* " + ActualTarget + " (originally " + target + ") / " + context + " */ " + "<br>border: " + border + "px; " + "<br>margin: " + MarginResult + "%; " + "<br>padding: " + PaddingResult+ "%;" + "<br> </span>}"
    }).hide().appendTo("#code-results").fadeIn();
   });

}); 

});

但是当有人根本没有输入数字时,我会在结果中得到NaN?如何使用此代码摆脱它?另外我希望0仍然显示为0可以用这个吗?

编辑:实际上我喜欢当有人没有输入数字而不是NaN时我得到0作为结果,这可能吗?

1 个答案:

答案 0 :(得分:4)

你可以使用这个函数isNaN()

进行测试
var myNumber = 'hello';
if (isNaN(myNumber)) 
    myNumber = 0;

console.log(myNumber); // return 0

编辑:测试多个值的实现:

(function(global, $) {
    function isNan(valuesOrg) {
        values = $.isArray(valuesOrg) ? valuesOrg : [valuesOrg];
        results = values.map(function(value) {
            return isNaN(value);
        });

        if (!$.isArray(valuesOrg)) {
            return results[0];
        }

        return results;
    }

    global.myIsNane = isNan;
})(window, jQuery);

console.info(myIsNane('gh'));
console.info(myIsNane(90));
console.info(myIsNane(['oo', 00, 'bb', 84]));