Javascript 变量可见性
Javascript variable visibility
我是 javascript 世界的新人。阅读有关变量范围的信息,我想我明白了。我做了一些实验,这里的情况给了我意想不到的结果。这就是我的意思
var x = 0;
function set(){
x++;
}
set();
console.log(x) // 1
此时脚本的 x 值如预期的那样为 1
total = 0;
var id = setInterval(function(){
total++;
}, 10);
console.log(total); // 0
在脚本的这一点上,total 的值始终为 0。我已经检查过,我确定 total 的值增加了。那么第二个例子有什么问题,为什么全局变量total的值没有改变呢?
您正在使用 setInterval,它会创建一个间隔 在 之后定期执行函数(作为参数传递给 setInterval 函数),
阅读https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval
所以,这里-
total = 0;
var id = setInterval(function(){
total++;
}, 10);
console.log(total); // 0
console.log(total); is executed before then the function inside the `setInterval` executes(aftyer a delay of 10ms).
你可以试试这个
total = 0;
var id = setInterval(function(){
total++;
console.log(total);
}, 10);
在这种情况下,总数在递增后打印
这是因为 java 脚本是异步的。 console.log 将首先执行,然后执行 setInterval 中的函数,因为它已被赋予 10 毫秒的延迟...
要查看 'total' 的增量值,您可以 运行 在 setInterval 之后的下面给出的代码。
window.setTimeout(function(){
console.log(total);
}, 10);
我是 javascript 世界的新人。阅读有关变量范围的信息,我想我明白了。我做了一些实验,这里的情况给了我意想不到的结果。这就是我的意思
var x = 0;
function set(){
x++;
}
set();
console.log(x) // 1
此时脚本的 x 值如预期的那样为 1
total = 0;
var id = setInterval(function(){
total++;
}, 10);
console.log(total); // 0
在脚本的这一点上,total 的值始终为 0。我已经检查过,我确定 total 的值增加了。那么第二个例子有什么问题,为什么全局变量total的值没有改变呢?
您正在使用 setInterval,它会创建一个间隔 在 之后定期执行函数(作为参数传递给 setInterval 函数),
阅读https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval
所以,这里-
total = 0;
var id = setInterval(function(){
total++;
}, 10);
console.log(total); // 0
console.log(total); is executed before then the function inside the `setInterval` executes(aftyer a delay of 10ms).
你可以试试这个
total = 0;
var id = setInterval(function(){
total++;
console.log(total);
}, 10);
在这种情况下,总数在递增后打印
这是因为 java 脚本是异步的。 console.log 将首先执行,然后执行 setInterval 中的函数,因为它已被赋予 10 毫秒的延迟...
要查看 'total' 的增量值,您可以 运行 在 setInterval 之后的下面给出的代码。
window.setTimeout(function(){
console.log(total);
}, 10);