回调函数的Javascript无法正常工作

时间:2016-03-15 16:39:11

标签: javascript

这是我的javascript程序,它应该在代码的底部输出alert语句但不适用。为什么?

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

3 个答案:

答案 0 :(得分:3)

您需要返回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 + ".");

您可以以更紧凑的方式重写代码:

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

答案 1 :(得分:2)

除了Pointy提到的拼写错误,如果我正确读取它,你永远不会从均值返回值,尝试返回总数

答案 2 :(得分:0)

您必须在回调函数中返回总计,并确保未将值变量键入为值。