我有这个问题,不知怎的,我无法解决它。我需要我的函数来打印counter1(1,2,3)然后我需要我的counter2从零开始计数,而不是继续counter1。 (counter1和counter2异步递增) 我需要打印如下计数:1,2,3,1,2,3。
function ukol2() {
var count = 0;
function makeCounter() {
return function() {
count++;
console.log(count);
};
}
var counter1 = makeCounter();
counter1(); //1
counter1(); //2
counter1(); //3
var counter2 = makeCounter();
counter2(); //4
counter2(); //5
counter2(); //6
}
答案 0 :(得分:4)
您的count
变量是全局变量,请将其放入函数makeCounter
。
function ukol2() {
function makeCounter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
var counter1 = makeCounter();
counter1(); //1
counter1(); //2
counter1(); //3
var counter2 = makeCounter();
counter2(); //4
counter2(); //5
counter2(); //6
}
ukol2();

请参阅?现在你的计数器会独立增加。
更新:根据@DiamondDrake的建议:
将此var count = 0;
更改为let count = 0;
以获取范围
let语句声明一个块作用域局部变量,可选择将其初始化为一个值。