This question already has answers here:
What does this symbol mean in JavaScript?
(1个答案)
What does a comma do in JavaScript expressions?
(6个答案)
When is the comma operator useful?
(13个回答)
去年关闭。
我不知道代码:here中的
作品:
(1个答案)
What does a comma do in JavaScript expressions?
(6个答案)
When is the comma operator useful?
(13个回答)
去年关闭。
我不知道代码:here中的
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;