计算输入字段时接收Javascript NaN

时间:2020-07-13 02:22:22

标签: javascript jquery

我正在使用Jquery来计算我正在编写的这个地毯计算器的输入总数。我遇到的问题是当我处于for循环中时能够输出值,但是当我不在两个循环中时都得到NaN,如下所示。

这也是我遇到的问题的有效示例-

https://codepen.io/CodeHero1/pen/abdjpgL

    $('#calculate-cost').on('click',function(){


    var widthTotalFeet = $('.room-width-feet').map((_,el) => el.value).get();
    var widthTotalInches = $('.room-width-inches').map((_,el) => el.value).get();

    var roomWidthTotalFeet = 0;  // total feet
    var roomWidthTotalInches = 0;  // total inches


    for(var i = 0; i < widthTotalFeet.length; i++) {

        roomWidthTotalFeet += parseInt(widthTotalFeet[i]);
        console.log('in array');
        //This increments correctly
        console.log('feet +' + roomWidthTotalFeet);
    }


    for(var i = 0; i < widthTotalInches.length; i++) {

        roomWidthTotalInches += parseInt(widthTotalInches[i]);
        //This increments correctly
        console.log('inches +' + roomWidthTotalInches);

    }

    var roomFeetAndInches = parseFloat(roomWidthTotalFeet + '.' + roomWidthTotalInches);

    

        //Receiving NaN on these console logs
        console.log('Parse ' + roomFeetAndInches);
        console.log('room widht feet=' + roomWidthTotalFeet);
        console.log('room widht inches=' + roomWidthTotalInches);


});

2 个答案:

答案 0 :(得分:1)

问题出在您使用parseInt上。 widthTotalFeetwidthTotalInches数组可能看起来像这样:['1','', '2'] ...其中empty string放置在任何空白字段中。如果您执行parseInt(''),则会得到NaN。要解决此问题,您应该排除空字符串或确保它们在循环中添加0

答案 1 :(得分:0)

您确定roomWidthTotalFeetroomWidthTotalInches没有尾随空格吗?尝试像这样进行浮点转换:

var roomFeetAndInches = parseFloat(trim(roomWidthTotalFeet) + "." + trim(roomWidthTotalInches));

此外,最好使用双引号代替单引号...

相关问题