我想将我从mysql获得的结果推送到一个空数组(totalJuice)

var sqlgetgauge =
"SELECT juice1_num FROM `customers_out` WHERE MONTH(date)=4 ";

   connection.query(sqlgetgauge, function(err, results, field) {
        if (err) throw err;


        for (i = 0; i < results.length; i++) {


            var numberjuice1 = Number(results[i].juice1_num / 100);

            var totalJuice = [];

            totalJuice.push(numberjuice1);
            console.log(totalJuice);

            //This is a Gauge Update
            juice_num_1.update({
                value: numberjuice1,
            });

        }


    });


但是这段代码不断通过console.log(totalJuice)向我显示结果;

gauge_picker.js:85 [0.5]
gauge_picker.js:85 [0.02]
gauge_picker.js:85 [0.02]

我期望数组将是[0.5,0.02,0.02]

还有一个问题是我如何才能得到这个数组的总数?

最佳答案

你的问题是这个声明

var totalJuice = [];


因为它在您的for循环内,所以每次都会重置该数组,这意味着您只会获得数组中的最后一个值。您需要将该声明移到for循环之前,例如

var totalJuice = [];
for (i = 0; i < results.length; i++) {
     ...


要获得所有值的总和,可以在循环后执行

sum = totalJuice.reduce((c, v) => c + v);

07-28 09:22