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

标签 javascript jquery

似乎无法将 Not a Number 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 !

任何帮助都会很棒!

最佳答案

替换

++value;

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

JSFiddle

关于javascript - 无法将 NaN 替换为 0 - 尝试了 rapply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895730/

相关文章:

jquery - Rails 3 中添加嵌套表单的计数器?

javascript - 如何检测 socket.io 传输何时发生变化? (事件或某事)

javascript - 通过对数组进行排序判断数组是否有重复元素

javascript - 以 url 作为参数的 JSON 调用

javascript - Jquery 选择器使用脚本更新

javascript - 如何隐藏jstree中未选中的checknode

javascript - Vue2理解:class attribute

javascript - 表单数据和复选框

jquery - 如何通过 jQuery 将隐式部分包装在 HTML 5 中?

javascript - 缩略图周围的灯箱 2 边框