如何用javascript添加数组元素值? [英] how to add array element values with javascript?
问题描述
我不是在谈论将元素添加到一起,而是将它们的值添加到另一个单独的变量。
I am NOT talking about adding elements together, but their values to another separate variable.
像这样:
var TOTAL = 0;
for (i=0; i<10; i++){
TOTAL += myArray[i]
}
使用此代码,TOTAL不会将数学元素值一起添加,但它会将它们添加到彼此旁边,所以如果 myArr [1] = 10
和 myArr [2] = 10
然后 TOTAL
将 1010
而不是 20
。
With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10
and myArr[2] = 10
then TOTAL
will be 1010
instead of 20
.
我该怎么写我想要的东西?
How should I write what I want ?
谢谢
推荐答案
听起来您的数组元素是字符串,尝试将它们转换为添加时的数字:
Sounds like your array elements are Strings, try to convert them to Number when adding:
var total = 0;
for (var i=0; i<10; i++){
total += +myArray[i];
}
请注意,我使用的是一元加运算符( + myArray [i]
),这是确保添加数字而不是连接字符串的常用方法。
Note that I use the unary plus operator (+myArray[i]
), this is one common way to make sure you are adding up numbers, not concatenating strings.
这篇关于如何用javascript添加数组元素值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!