如何在不指定任何值的情况下创建全局整数变量?

时间:2014-04-25 11:47:24

标签: javascript

var add = function() {
        var total_income = 0;
        for (var i = 0; i < income_amount.length; i++) {
            total_income = total_income + income_amount[i];

        }
        return total_income;
    }
    var balance = add();

我的函数没有返回更新的值,它正在分配当前值,即0,那么我怎样才能得到更新的值

2 个答案:

答案 0 :(得分:0)

我假设了income_amount,结果我得到了300

 var income_amount=[100,200];
    var add = function() {
            var total_income = 0;
            for (var i = 0; i < income_amount.length; i++) {
                total_income = total_income + income_amount[i];

            }
            console.log(total_income);
            return total_income;
    }
    var balance = add();

您的代码工作正常。希望它有所帮助。

答案 1 :(得分:0)

如果我尝试使用您的代码,结果是正确的,请查看this jsFiddle

我初始化了income_amount变量for test:

var income_amount = [1,2,3,4];