首页 > 解决方案 > JS嵌套问题,变量以任何方式返回未识别

问题描述

我试图为 JS 中的编程课程做一个复利计算器,结果遇到了一个问题:我在较高级别初始化的变量在较低级别中无法识别。我读到的恰恰相反,我读到了嵌套函数、函数范围和所有内容,并试图将 CompoundI 函数放在另一个函数中,但直到现在还没有解决它。一个想法 ?

/* TODO
 * 10 000€ placed for 20 years at 4% per year
 */

;
(function () {
    'use strict';

    var cash;
    var tau;
    var yea;
    var an;

    cash = parseInt(prompt("T'as CB sur ta CB ?", "10000"));
    tau = parseInt(prompt("% d'intérêt annuel", "4"));
    yea = parseInt(prompt("Nombre d'années", "20"));
    an = 0;

    var compoundI = function (cash, tau, yea, an) {
        while (an < yea) {
            an++;
            cash = cash * (100 + tau) / 100;
            compoundI(cash, tau, yea, an);
            alert(cash);
            break;
        }
    //here, alert(yea) gives "unidentified, so the while loop can't happen. 
    //Why my declared variables aren't recognized in the compoundI function ?
    }
})();

标签: javascript

解决方案


仅仅因为您将参数命名为与变量compoundI相同的参数并不能使其神奇地工作,您仍然需要compoundI最初调用。请参阅下面我的解决方案的倒数第二行

更直接地说,您可以将函数参数命名为任何名称,它们不必与保存您传递给它的值的变量同名。

解决方案

/* TODO
 * 10 000€ placed for 20 years at 4% per year
 */

;
(function () {
    'use strict';

    var cash;
    var tau;
    var yea;
    var an;

    cash = parseInt(prompt("T'as CB sur ta CB ?", "10000"));
    tau = parseInt(prompt("% d'intérêt annuel", "4"));
    yea = parseInt(prompt("Nombre d'années", "20"));
    an = 0;

    var compoundI = function (cash, tau, yea, an) {
        while (an < yea) {
            an++;
            cash = cash * (100 + tau) / 100;
            compoundI(cash, tau, yea, an);
            console.log(cash);
            break;
        }
    }
    compoundI(cash, tau, yea, an);
})();


推荐阅读