如何使用let声明作为表达式? [英] How to use let declarations as expressions?

查看:306
本文介绍了如何使用let声明作为表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用let表达式,但是以下代码不起作用:

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

我应该怎么做?

推荐答案

以下是一种糖...

let x = 1
console.log(x)

如果没有varconstlet,我们可以使用函数来绑定变量

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)

并且因为JavaScript函数可以具有多个1个参数,所以如果需要,您可以使用单个函数绑定多个变量

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)

关于您的三元表达式

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

这些都不要求任何奇特的语法或语言功能-以下内容可以在我能想到的几乎所有JS实现中使用

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

这篇关于如何使用let声明作为表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆