How to use let declarations as expressions?

霸气de小男生 提交于 2020-01-17 07:21:41

问题


I want to use let expressions, but the following code doesn't work:

true ? (let x=1, let y=2, x+y) : (let x=3, let y=4, x-y); // SyntaxError

How am I supposed to do this?


回答1:


Unfortunately, Javascript lacks lisp-style let expressions. However, since there are default parameters and arrow functions we can mimic them:

const let_ = f => f();

console.log(
  true ? let_((x = 1, y = 2) => x + y) : let_((x = 3, y = 4) => x - y) // 3
);

To be honest, this is a bit tedious and the code is pretty verbose. The following recursive use case might be more convincing:

const let_ = f => f();

const fact = n => let_(
  (aux = (n, acc) => n === 1 ? acc : aux(n - 1, acc * n)) => aux(n, 1)
);

console.log(
  fact(5) // 120
);

It is questionable whether this is idiomatic Javascript, but it was litteraly the first time I used default parameters in my code.




回答2:


The following is a kind of sugar...

let x = 1
console.log(x)

Without var, const, or let, we could use functions to bind variables

// let x = 1; console.log(x);
(x => console.log(x)) (1)

Of course this works if you have multiple variables too

(x =>
  (y => console.log(x + y))) (1) (2)

And because JavaScript functions can have more then 1 parameter, you could bind multiple variables using a single function, if desired

((x,y) => console.log(x + y)) (1,2)

As for your ternary expression

true
  ? ((x,y) => console.log(x + y)) (1,2)
  : ((x,y) => console.log(x - y)) (1,2)
// 3

false
  ? ((x,y) => console.log(x + y)) (1,2)
  : ((x,y) => console.log(x - y)) (1,2)
// -1

None of this requires any fanciful syntax or language features either – the following would work on pretty much any implementation of JS that I can think of

true
  ? (function (x,y) { console.log(x + y) }) (1,2)
  : (function (x,y) { console.log(x - y) }) (1,2)
// 3

false
  ? (function (x,y) { console.log(x + y) }) (1,2)
  : (function (x,y) { console.log(x - y) }) (1,2)
// -1


来源:https://stackoverflow.com/questions/43822109/how-to-use-let-declarations-as-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!