首页 > 解决方案 > 如何使用 jQuery 每个函数检查 NaN 的数组值?

问题描述

我有这些从数据库中获取数据的 HTML 代码。我将一个数组设置为 HTML 输入。

html代码

<table>
    <thead>
        <tr>
            <th>Category</th>
            <th>January</th>
            <th>February</th>
        </tr> 
    </thead>
    <tbody>
        <?php
        $sql = DB::getInstance()->FetchArray("select * from table");
        if(count($sql) > 0)
        {
            foreach($sql as $row)
            {
                $i = 0;
                if($i == 0)
                {?>
                    <tr>
                        <td><input type="text" class="cat1" id="cat1" name="cat1[]" value="<?php echo $row['CATEGORY']; ?>" placeholder="" readonly></td>
                        <td><input type="text" class="jan1" id="jan1" name="jan1[]" value="<?php echo (($row['MONTH']=='JANUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
                        <td><input type="text" class="feb1" id="feb1" name="feb1[]" value="<?php echo (($row['MONTH']=='FEBRUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
                    </tr> 
                <?php
                }
                else
                {?>
                    <tr>
                        <td></td>
                        <td><input type="text" class="jan1" id="jan1" name="jan1[]" value="<?php echo (($row['MONTH']=='JANUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
                        <td><input type="text" class="feb1" id="feb1" name="feb1[]" value="<?php echo (($row['MONTH']=='FEBRUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
                    </tr>
                <?php
                }
                $i++;
        }
        ?>
        <tr>
            <td colspan="2" style="text-align:right;">Total</td>
            <td><input type="text" class="form-control inputnumberwith2decimals total_jan1" id="total_jan1" name="" value="" placeholder="" readonly></td>
            <td><input type="text" class="form-control inputnumberwith2decimals total_feb1" id="total_feb1" name="" value="" placeholder="" readonly></td> 
        </tr>
    </tbody> 
</table>

jan1[] 的值在 console.log 中显示为

NaN
1000
3000
NaN

当我尝试对 jan1[] 求和时,输出显示为 NaN,因为某些数组值是 NaN。如何将 NaN 值设置为 0 并进行总和计算?

我想要实现的是总结如下的价值

CATEGORY        JANUARY     FEBRUARY
BANANA          NaN         NaN
                1000        NaN
                2000        NaN
                NaN         NaN

TOTAL           3000        0

这是jQuery的代码。

<script>
    $(document).ready(function(){
        var sum_jan1 = parseFloat(0);
        $(".jan1").each(function(){
            var value = parseFloat($(this).val());
            sum_jan1 += value;
        });
        $('#total_jan1').val(sum_jan1);
    });
</script>

谢谢。

标签: javascriptjqueryeachnan

解决方案


您只需在 sum 函数中将 NaN 值转换为 0。以下是使用的示例reduce

const arr = [NaN, 1000, 3000, NaN];
const sum = arr.reduce((acc, num) => acc += num || 0, 0);
console.log(sum);
// 4000


推荐阅读