我正在尝试在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)
,但结果是一样的。
答案 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);