JavaScript
我得到00.10.10.20.20.050.050.05
作为输出。
但是,我希望总和为.75
var array = ['0.1','0.1','0.2','0.2','0.05','0.05','0.05']
var sum = 0;
function sumArray() {
var random = Math.floor(Math.random() * 100);
for (i=0; i < array.length ; i++) {
sum +=array[i];
}
}
sumArray();
alert(sum);
答案 0 :(得分:2)
实际上,您是在串联字符串(您的数组上有字符串)。只需解析您的字符串即可:
var array = ['0.1','0.1','0.2','0.2','0.05','0.05','0.05']
var sum = 0;
function sumArray() {
var random = Math.floor(Math.random() * 100);
for (i=0; i < array.length ; i++) {
sum += parseFloat(array[i]);
}
}
sumArray();
alert(sum);
答案 1 :(得分:-1)
let array = ['0.1','0.1','0.2','0.2','0.05','0.05','0.05'];
let sum = array.reduce((a, b) => parseFloat(a) + parseFloat(b));
console.log(sum);