Here is my javascript program and it supposed to output the alert statement at the bottom of the code but is not apppearing. Why is it?
//function mean
function mean(values, callback) {
var total = 0;
for (var i = 0, max = values.length; i < max; i++) {
if (typeof callback === "function") {
total += callback(value[i]);
} else {
total += values[i];
}
}
}
var result = mean([2, 5, 7, 11, 4], function (x) {
return 2 * x;
});
alert("The result mean is " + result + ".");
You need to return total
and change value
to values
.
function mean(values, callback) {
var total = 0;
for (var i = 0, max = values.length; i < max; i++) {
if (typeof callback === "function") {
total += callback(values[i]);
} else {
total += values[i];
}
}
return total;
}
var result = mean([2, 5, 7, 11, 4], function (x) {
return 2 * x;
});
alert("The result mean is " + result + ".");
You can rewrite the code to a more compact way:
function mean(values, callback) {
callback = callback || function (x) { return x; };
return values.reduce(function (r, a) {
return r + callback(a);
}, 0);
}
var result = mean([2, 5, 7, 11, 4], function (x) {
return 2 * x;
});
alert("The result mean is " + result + ".");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments