[英]Increment global variable inside function
Can someone tell me why the global variable is not affecting?有人能告诉我为什么全局变量没有影响吗? the local variable in function works.函数中的局部变量有效。 But not outside the function.但不是在函数之外。
let increment = 0;
button.addEventListener("click", function(){
increment++;
console.log(increment); // Works!
});
console.log(increment); // Not incrementing
This is because addEventListener
works asynchronously.这是因为addEventListener
异步工作。 The console.log
statement at the last line of your code gets executed before the callback of your event listener is run and thus the value of your increment
variabe is still 0.代码最后一行的console.log
语句在事件侦听器的回调运行之前执行,因此increment
变量的值仍然为 0。
This version might help demonstrate what's happening:此版本可能有助于演示正在发生的事情:
let increment = 0; const button = document.getElementById('foo'); const output = document.getElementById('output'); const updateOutput = function() { output.innerHTML = `Value is ${increment} at ${new Date().toString().substring(16, 24)}`; } button.addEventListener("click", function(){ increment++; updateOutput(); }); setInterval(updateOutput, 1000) console.log(`External call, value: ${increment}`);
<div id="output"></div> <hr/> <div><button id="foo">Increment</button></div>
Choose "Run code snippet" to see it in action.选择“运行代码片段”以查看它的运行情况。 It tells you the current value of the (global) increment
variable every second.它每秒告诉您(全局) increment
变量的当前值。 It also updates when you click the button and thereby increase the value.单击按钮时它也会更新,从而增加值。 Both functions are accessing the same global increment
variable.两个函数都访问相同的全局increment
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.