本文共 2613 字,大约阅读时间需要 8 分钟。
java三目运算符简化代码
by Matt Granmoe
通过Matt Granmoe
Recently, a co-worker who is learning to love JavaScript came to me asking if there was a simple way to take a function like this:
最近,一个正在学习爱JavaScript的同事来找我,问是否有一种简单的方法来实现这样的功能:
and return bar: parseBar(bar)
when bar
is passed. But somehow prevent returning bar
as undefined
when bar
is not passed, since some usages of this in the codebase don’t pass it. He was specifically looking for a way to do this that wouldn’t require any refactoring (like changing from an implicit return to a full function body, using if/else, creating a separate function to do filtering of certain values, etc).
和回报bar: parseBar(bar)
时, bar
传递。 但是以某种方式可以防止在未传递bar
时将bar
返回为undefined
,因为在代码库中对此的某些用法不会传递它。 他专门在寻找一种不需要任何重构的方法(例如,从隐式返回更改为完整的函数主体,使用if / else,创建单独的函数以对某些值进行过滤等)。
After some hacking in the JavaScript console, I realized that the following is possible:
在JavaScript控制台中进行了一些修改之后,我意识到可以实现以下目的:
Here’s a condensed example to throw in the console if you want:
如果需要,这是一个精简的示例可放入控制台:
This is possible due to two things. First, the fact that, although the spread operator can’t occur anywhere as a token, it can be applied to literally any data type in the entire language.
由于两件事,这是可能的。 首先,尽管扩展运算符不能作为令牌出现在任何地方,但实际上可以将其应用于整个语言中的任何数据类型 。
It’s commonly known that Object
, Array
, Set
and similar are iterable. The fact that all primitive types are also valid operands of the spread operator allows us to spread literally any expression since all expressions will evaluate to some value after being executed.
众所周知, Object
, Array
, Set
和类似Object
是可迭代的。 所有原始类型也是扩展运算符的有效操作数的事实使我们能够按字面意义扩展任何表达式,因为所有表达式在执行后都会求值。
If you don’t believe me, throw the following in the console:
如果您不相信我,请在控制台中输入以下内容:
The second thing that helps us is that spreading an “empty” value results in a no-op.
帮助我们的第二件事是,传播“空”值会导致无操作。
Two quick examples of how this back alley of JavaScript might be used:
两个简单的示例说明如何使用JavaScript的后巷:
Guard expressions (à la React’s JSX, and also what was used to solve the original problem mentioned in this post): ...(foo && parseFoo(foo))
保护表达式(如React的JSX,以及用于解决本文中提到的原始问题的表达式): ...(foo && parseFoo(foo))
“Default” expressions: ...(someValue || someDefault)
“默认”表达式: ...(someValue || someDefault)
A more generic way to refer to all these things might be “spread expressions.” However, I’d now like to say “spread expressions” not as a noun but as a suggestion. Go forth with the knowledge that you can spread all the expressions! ?
引用所有这些内容的更通用的方法可能是“扩展表达式”。 但是,我现在想说的“扩展表达”不是一个名词,而是一个建议。 知道您可以传播所有表情! ?
翻译自:
java三目运算符简化代码
转载地址:http://vdewd.baihongyu.com/