I'm attempting to get a coefficient of variation calculator working with jQuery, and can't seem to get it to output a correct answer.
My current code:
var fields = $('#cvform').serializeArray();
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
var delta=(field.value-mean);
var mean=(mean+delta/num);
var m2=(m开发者_如何学运维2+delta*(field.value-mean));
var total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + delta + m2 + num + total + cov + "</span>").appendTo('#cvdisplay');
When I attempt to output the values after, it tells me that delta is undefined, mean m2 and total are = 0, and num is output correctly. Cov is simply output as NaN. The array of #cvform is simply text inputs that can only be numbers. Can anyone point me in the right direction of getting this to function?
You declare delta within a function, so it isn't visible outside the for loop. Move its declaration out of the each block and it will be found.
var fields = $('#cvform').serializeArray();
var num = 0,
mean = 0,
m2 = 0,
total = 0,
delta = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
delta=(field.value-mean);
mean=(mean+delta/num);
m2=(m2+delta*(field.value-mean));
total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + (delta + m2 + num + total + cov) + "</span>").appendTo('#cvdisplay');
精彩评论