[英]How one function access a variable value from another function in JavaScript?
let count = 0; function increment(){ count += 1; console.log(count); } function decrement(){ count -= 1; console.log(count); } increment(); decrement();
Calling increment()
will give count = 1
and then calling decrement()
will give count = 0
.调用
increment()
将给出count = 1
,然后调用decrement()
将给出count = 0
。 How does the second function get the value of count from the first function?第二个 function 如何从第一个 function 中获取 count 的值?
You have to return that value from a function and pass count as argument to the functions:您必须从 function 返回该值并将计数作为参数传递给函数:
let count = 0;
function increment(count){
count += 1;
console.log(count);
return count;
}
function decrement(count){
count -= 1;
console.log(count);
return count;
}
var value = increment(count);
value = decrement(count);
value = decrement(increment(count)); //no change of course
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.