修改变量不起作用的函数 - Javascript

时间:2015-02-11 13:50:58

标签: javascript function

我的问题涉及3个变量:

var modifyForce = 2;
var forceBase = 15;
var Force = (forceBase + modifyForce);

显示17 Force

正在运作的第一个功能是:

{
    Force++;
    document.getElementById("Force").innerHTML = Force;
}

每当我调用它时,它会向Force添加+1

但第二个功能:

{
    forceBase++;
    document.getElementById("Force").innerHTML = Force;
}

不向Force添加+1。因为它应该向forceBase和Force = forceBase + modifyForce添加+1,那么它应该向Force添加1 ...我认为。

我的目标是拥有一个" forceBase"统计+ a" modifyForce"为了获得总数" Force"

我可能遗漏了一些简单的东西,但我无法找到。 :/

谢谢:)

5 个答案:

答案 0 :(得分:2)

问题是您没有将Force更新为等于新的forceBase + modifyForce。除了声明,ForceforceBasemodifyForce没有任何关联,您必须手动为其分配新值。你应该改变你的代码:

{
    forceBase++;
    Force = forceBase + modifyForce;
    document.getElementById("Force").innerHTML = Force;
}

请注意,如果在其他功能(例如您发布的第一个功能)中更改Force,则会重置这些更改。

答案 1 :(得分:2)

似乎没有人建议过这个......

如果您希望Force始终为forceBase + modifyForce,请将其设为功能。

function Force(){
    return forceBase + modifyForce
}

现在使这项工作成功(注意现在使用()调用Force:

{
    forceBase++;
    document.getElementById("Force").innerHTML = Force();
}

答案 2 :(得分:2)

var modifyForce = 2;
var forceBase = 15;
var Force = (forceBase + modifyForce);

使用forceBase + modifyForce计算一次力 声明后,您只需将号码保存在Force

如果您想使用Force作为函数将modifyForce添加到forceBase,请使用类似

的内容
var Force = function () {
    return forceBase + modifyForce;
}

但你不能像Force ++那样增加它:P

答案 3 :(得分:1)

您修改forceBase的代码块不会重新计算Force的更新值。

为了简化这一点,我建议你将重新计算和输出移动到这样一个独特的函数中:

var modifyForce = 2;
var forceBase = 15;

function updateForce() {
    var Force = (forceBase + modifyForce);
    document.getElementById("Force").innerHTML = Force;
}

// Output the current value of Force
updateForce(); // output is 17

forceBase++;
updateForce(); // output is 18

modifyForce++;
updateForce(); // output is 19

答案 4 :(得分:1)

最好的方法是创建一个类:

var objForce = {
    modifyForce: 2,
    forceBase: 15,
    Force: 17,
    reCalculate: function() { 
        this.Force = this.modifyForce + this.forceBase;
    }
};
objForce.forceBase++;
objForce.reCalculate();
document.getElementById("Force").innerHTML = objForce.Force;