java箭头函数返回(x ++,x)[重复]

问题描述 投票:6回答:3

我不知道代码:const countFrom = x => () => (x++, x);中的here,作品:

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;}
javascript arrow-functions
3个回答
2
投票

x是外部(x =>)函数内部的变量,因此所有内部函数(() => (x++, x))共享同一变量。每当内部函数执行时,x++帖子都会递增该变量。逗号运算符(..., x)计算得出最后一个逗号分隔的表达式,在这种情况下为x

如果没有逗号运算符,可能更容易理解:

 const counter = x => () => x = x + 1;

0
投票

//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;}

0
投票

如果您了解某些方面,这很简单:

  1. 第一行中有两个函数,不仅有一个:第一个返回第二个函数()=> (x++,x)(请参阅closure是什么]
  2. 在圆括号内,您看到逗号运算符,并且语句的结果是逗号运算符的最后一个操作数(此处为x),
  3. 圆括号的作用类似于return x,即=> (x)=> return x相同
© www.soinside.com 2019 - 2024. All rights reserved.