[英]Update global variables in two functions JavaScript
虽然我知道 JavaScript 中的“全局 scope、function scope、块范围”。但我陷入了这个代码块。
我将代码的逻辑简化如下。 我期望的是,执行 function 中的console.log(a, b, c)
将是 a = 3, b = 6, c = 9。但我实际得到的是 a = 0, b = 0, c = 0 . 出了什么问题以及如何解决这个问题? 谢谢
(function() {
let a,b,c;
let conditions = [-1, 1, 2, 3 ];
const execute = () => {
for (let i=0; i<conditions.length; i++) {
if (conditions[i] < 0) {
a = 0;
b = 0;
c = 0;
} else if (conditions[i] > 0) {
update(a, b, c);
}
}
console.log(a,b,c);
}
const update = (a, b, c) => {
a = a + 1;
b = b + 2;
c = c + 3;
}
execute();
})()
在这里,通过不向update()
声明参数,对父 scope 中的变量进行赋值。
(function() { let a,b,c; let conditions = [-1, 1, 2, 3 ]; const execute = () => { for (let i=0; i<conditions.length; i++) { if (conditions[i] < 0) { a = 0; b = 0; c = 0; } else if (conditions[i] > 0) { update(); // edit } } console.log(a,b,c); } const update = () => { a = a + 1; b = b + 2; c = c + 3; } execute(); })()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.