java-脚本箭头函数returns (x++,x)
java-script arrow function returns (x++,x)
我不知道代码如何:const countFrom = x => () => (x++, x);
来自 ,
作品:
const countFrom = x => () => (x++, x);
let a = countFrom(1)
console.log('output:', a()) // output: 2
console.log('output:', a()) // output: 3
console.log('output:', a()) // output: 4
console.log('output:', a()) // output: 5
.as-console-wrapper {min-height: 100%!important; top: 0;}
x
是外部函数(x =>
)内部的一个变量,因此所有内部函数(() => (x++, x)
)共享同一个变量。 x++
post 每当内部函数执行时都会递增该变量。逗号运算符 (..., x
) 计算最后一个逗号分隔的表达式,在本例中为 x
。
没有逗号运算符可能更容易理解:
const counter = x => () => x = x + 1;
//const countFrom = x => () => (x++, x);
//Lets refactor the code a bit:
function countFrom(x){
return function(){
x++;
return x;
}
}
let a = countFrom(1)
//now a is the returned function at line 5, and x is stored as a local variable.
console.log('output:', a()) // output: 2 you call the function at line 5 so it adds 1 to x and returns it
.as-console-wrapper {min-height: 100%!important; top: 0;}
了解了一些就很简单了:
- 你在第一行有两个函数,不仅仅是一个:第一个returns第二个函数
()=> (x++,x)
(看看closure
是什么)
- 在圆括号内,您会看到逗号运算符,语句的结果是逗号运算符的最后一个操作数(此处为 x),
- 圆括号的作用类似于
return x
,即=> (x)
与=> return x
相同
我不知道代码如何:const countFrom = x => () => (x++, x);
来自
const countFrom = x => () => (x++, x);
let a = countFrom(1)
console.log('output:', a()) // output: 2
console.log('output:', a()) // output: 3
console.log('output:', a()) // output: 4
console.log('output:', a()) // output: 5
.as-console-wrapper {min-height: 100%!important; top: 0;}
x
是外部函数(x =>
)内部的一个变量,因此所有内部函数(() => (x++, x)
)共享同一个变量。 x++
post 每当内部函数执行时都会递增该变量。逗号运算符 (..., x
) 计算最后一个逗号分隔的表达式,在本例中为 x
。
没有逗号运算符可能更容易理解:
const counter = x => () => x = x + 1;
//const countFrom = x => () => (x++, x);
//Lets refactor the code a bit:
function countFrom(x){
return function(){
x++;
return x;
}
}
let a = countFrom(1)
//now a is the returned function at line 5, and x is stored as a local variable.
console.log('output:', a()) // output: 2 you call the function at line 5 so it adds 1 to x and returns it
.as-console-wrapper {min-height: 100%!important; top: 0;}
了解了一些就很简单了:
- 你在第一行有两个函数,不仅仅是一个:第一个returns第二个函数
()=> (x++,x)
(看看closure
是什么) - 在圆括号内,您会看到逗号运算符,语句的结果是逗号运算符的最后一个操作数(此处为 x),
- 圆括号的作用类似于
return x
,即=> (x)
与=> return x
相同