简体   繁体   中英

Javascript with callback function not working

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 + "."); 

以及Pointy提到的错别字,如果我没看错,您永远不会从均值中返回值,请尝试返回合计

您必须在回调函数中返回total,并确保没有将values变量键入为value。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM