求和数返回NaN

时间:2016-03-18 17:47:12

标签: javascript jquery each nan

我正在尝试在div中做一些数字,所以,我做了:

$(document).ready(function() {
    var numbers, sumNumbers;

    $(".item").each(function() {
  	numbers = $(this).children().text();
        numbers = +numbers;
    
        sumNumbers += numbers;
    });
  
    console.log(sumNumbers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <span class="itemNum">0</span>
</div>

<div class="item">
  <span class="itemNum">2</span>
</div>

<div class="item">
  <span class="itemNum">1</span>
</div>

但是,同样将numbers从文本转换为带有+numbers的数字会返回NaN,为什么?我已经尝试了Number(numbers),但结果是一样的。

2 个答案:

答案 0 :(得分:9)

您没有初始化sumNumbers,因此您获得undefined +数字= NaN

var numbers, sumNumbers = 0;

答案 1 :(得分:1)

试试这个

var numbers=0, sumNumbers=0; //initilize numbers & sumNumbers;

$(".item").each(function () {
    numbers = $(this).children().text() * 1; // *1 convert string to number

    sumNumbers += numbers;
});

console.log(sumNumbers);