无法将NaN替换为0 - 尝试了rapply

时间:2014-02-20 00:36:31

标签: javascript jquery

似乎无法将NaN错误替换为0。尝试使用rapply但不适合我。

window.onload = function () {
    var first = document.getElementById('firstFieldId'),
        second = document.getElementById('secondFieldId'),
        third = document.getElementById('thirdFieldId'),
        fourth = document.getElementById('fourthFieldId');

    first.onkeyup = function () {
        var value;

        // Get the value and remove the commas
        value = first.value.replace(/,/g, "");

        // Make it a number
        value = parseInt(value, 10);

        // Add one to it
        ++value;

        // Turn it back into a string
        value = String(value);

        // Put it in the other text box, formatted with commas
        second.value = numberWithCommas(value);
    };
    third.onkeyup = function () {
        var value;

        // Get the value and remove the commas
        value = third.value.replace(/,/g, "");

        // Make it a number
        value = parseInt(value, 10);

        // Add one to it
        ++value;

        // Turn it back into a string
        value = String(value);

        // Put it in the other text box, formatted with commas
        fourth.value = numberWithCommas(value);
    };

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
};

制作一个JSFiddle http://jsfiddle.net/7r5SF/2/ - 如果你在第一个或第三个字段中放一个数字,然后清除它,第二个或第四个字段将显示为NaN ...它需要说0

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

替换

++value;

value = isNaN(value) ? 0 : value+1

JSFiddle