【问题标题】:Javascript, problem to validate value after converting Nan to 0.00Javascript,将 Nan 转换为 0.00 后验证值的问题
【发布时间】:2021-02-22 23:14:51
【问题描述】:

最初,我有以下 javascript 来验证重量。但是要意识到有可能没有 selfDefinedGrid,这意味着权重将为 NaN。然后我添加了一个 if/else 语句来将 NaN 转换为 0.00。转换有效,但重量验证不再有效。请告知如何解决此问题,以便将 NaN 值转换为 0.00 并执行权重检查。

原文:

    $j( '#' + config.TableGridNames._02_SelfDefined + ' tbody tr td:nth-child(' + config.SelfDefinedGrid.Edit_Weight_Idx + ')' ).each( function ()
    {
        var row_index = $j( this ).closest( 'tr' ).index();
        /* skip over the header row; return is equivalent to continue */
        if ( row_index == 0 ) { return; }

        $j( this ).css( { 'background-color': 'white' } );
        var oWeight = $j( this ).find( 'input' );
        if ( !helper.isNumber( oWeight.val() ) || parseFloat( oWeight.val() ) < 0 || parseFloat( oWeight.val() ) > 1 )
        {
            $j( this ).css( { 'background-color': '#FFD1D1' } );
            blIsError = true;
        }

        decWeight = decWeight + parseFloat( oWeight.val() );
        console.log( 'Self-Defined (' + row_index.toString() + ') ' + decWeight.toString() );
    } );

更新:

    $j( '#' + config.TableGridNames._02_SelfDefined + ' tbody tr td:nth-child(' + config.SelfDefinedGrid.Edit_Weight_Idx + ')' ).each( function ()
    {
        var row_index = $j( this ).closest( 'tr' ).index();
        /* skip over the header row; return is equivalent to continue */
        if ( row_index == 0 ) { return; }

        $j( this ).css( { 'background-color': 'white' } );
        var oWeight = $j( this ).find( 'input' );

    if (oWeight.val() == 'NaN')
    {
    oWeight.val() = 0.00;
    }   else    {
            return oWeight.val();

        }

        if ( !helper.isNumber( oWeight.val() ) || parseFloat( oWeight.val() ) < 0 || parseFloat( oWeight.val() ) > 1 )
        {
            $j( this ).css( { 'background-color': '#FFD1D1' } );
            blIsError = true;
        }

        decWeight = decWeight + parseFloat( oWeight.val() );
        console.log( 'Self-Defined (' + row_index.toString() + ') ' + decWeight.toString() );
    } );

【问题讨论】:

    标签: javascript nan


    【解决方案1】:

    如果看起来您正试图将 0.0 分配给函数调用,那就是导致问题的原因。

    
    if (oWeight.val() == 'NaN') {
        oWeight.val() = 0.0;
    } else {
        return oWeight.val();
    }
    
    

    这是对上面代码的修复

    
    let val = 0.0;
    if (oWeight.val() == 'NaN') {
        val = 0.0;
    } else {
        val = oWeight.val();
    }
    
    

    更紧凑的解决方案

    
    let val = oWeight.val() == 'NaN' ? 0.0 : oWeight.val();
    
    

    那么,在任一示例中,您都可以使用val 代替oWeight.val()

    【讨论】:

    • 另外,如果您能够重写 oWeight.val() 函数本身,您可以添加一些检查以确保它始终返回一个数字。不过,我需要查看更多关于该解决方案的代码
    猜你喜欢
    • 2017-10-23
    • 2012-05-09
    • 2011-07-04
    • 2019-09-17
    • 1970-01-01
    • 2011-11-24
    • 2014-07-13
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多