Reputation:
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 + ".");
Upvotes: 1
Views: 102
Reputation: 386550
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 + ".");
Upvotes: 3
Reputation: 761
You have to return total in your callback function and make sure values variables are not typed as value.
Upvotes: 0
Reputation: 4227
Along with the typo mentioned by Pointy, If I am reading it right, you never return a value from mean, try returning total
Upvotes: 2