javascript - 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 ?
}
})();
解决方案
仅仅因为您将参数命名为与变量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);
})();
推荐阅读
- c# - unity禁用子旋转
- android-studio - 在 iPhone 模拟器上运行 Flutter 应用时偶尔出现 IDE 错误。FlutterApp.setLaunchMode 不能为 null
- react-native - React Native - 无法在 Android 上的 TextInput onChangeText 回调中修改文本
- python - 如何在看门狗中输入文件名作为模式
- powershell - 文件的 PS SHA512 哈希,输出为 base 64 编码字符串
- c# - 将位图保存为 jpg 时的 Pleora SDK 水平线伪影
- mysql - 如何选择最大值为 2 列的行
- maven - 我在tomcat 8中部署spring boot api嵌套异常是org.springframework.beans.factory.UnsatisfiedDependencyException
- excel - 从 Activex 控件映射变量 - [VBA]
- terminal - 使用 csplit 根据分隔符拆分文本文件时遇到问题