什么语法错误导致函数的 'text' 在此 JS 闭包中返回,而不是让它递增?
What syntax errors are causing the 'text' of the function to be returned in this JS closure, rather than having it increment?
我只是想创建一个递增函数,但我的运气为零。我只能设法得到这种类型的输出,或者我得到一个不递增的整数。
const count = () => {
let countUp = function(n) {
return function() {
n += 1;
return n;
}
};
return countUp;
};
console.log(count());
输出:
function(n) {
return function() {
n += 1;
return n;
}
}
下面是一个 ES5 脚本,它会在每次调用时递增一个计数器。下面的代码使用了 immediately invoked function expressions and closures.
//The number we want to start counting up from
var startAt = 0;
//Immediately invoke the anonymous outer function - this will return a function into our "count" variable. The closure will retain access to local variable j which is passed as an argument.
var count = (function(i) {
var j = i;
return function() {
j += 1;
return j;
}
}(startAt));
//Call count 10 times
var k;
for (k = 0; k < 10; k++) {
console.log(count());
}
下面是使用更简洁的 ES6 语法编写的相同代码:
const count = ((i) => {
var j = i;
return () => ++j;
})(0);
for (let k = 0; k < 10; k++) {
console.log(count());
}
我只是想创建一个递增函数,但我的运气为零。我只能设法得到这种类型的输出,或者我得到一个不递增的整数。
const count = () => {
let countUp = function(n) {
return function() {
n += 1;
return n;
}
};
return countUp;
};
console.log(count());
输出:
function(n) {
return function() {
n += 1;
return n;
}
}
下面是一个 ES5 脚本,它会在每次调用时递增一个计数器。下面的代码使用了 immediately invoked function expressions and closures.
//The number we want to start counting up from
var startAt = 0;
//Immediately invoke the anonymous outer function - this will return a function into our "count" variable. The closure will retain access to local variable j which is passed as an argument.
var count = (function(i) {
var j = i;
return function() {
j += 1;
return j;
}
}(startAt));
//Call count 10 times
var k;
for (k = 0; k < 10; k++) {
console.log(count());
}
下面是使用更简洁的 ES6 语法编写的相同代码:
const count = ((i) => {
var j = i;
return () => ++j;
})(0);
for (let k = 0; k < 10; k++) {
console.log(count());
}