简体   繁体   English

具有回调功能的Javascript无法正常工作

[英]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. 这是我的JavaScript程序,它应该在代码底部输出警告语句,但不适用。 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 . 您需要返回total并将value更改为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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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