写一个if-else语句的短缺,在一行中有两个case

Har*_*iec 2 javascript expression if-statement equals-operator

有一个javascript表达式将name变量赋给renamed变量.一个例外情况总是如此:

renamed =  name == 'John' ? 'Johnny' : name;
Run Code Online (Sandbox Code Playgroud)

但是,我想要两个排除:

  1. 将约翰改名为约翰尼
  2. 将Alex重命名为Alexander
  3. 所有其他名称都没有更改.

是否可以在一个字符串中写这个表达式?

renamed =  (name == 'John' || name == 'Alex') ? <____> : name;
Run Code Online (Sandbox Code Playgroud)

我需要在一个字符串中完成它.

谢谢.

the*_*eye 5

(name === 'John' && 'Johny') || (name === 'Alex' && 'Alexander') || name;
Run Code Online (Sandbox Code Playgroud)
  • 如果nameJohn,那么它将转到&&表达式中的下一部分并返回Johny.

  • 如果nameAlex,则在第一种情况下返回Alexander.

  • 如果它们都不是真的,那么按name原样返回.

演示

这个解决方案有效,因为在JavaScript中,&&运算符计算左边的表达式,如果它是假的,那么将返回该值,并且根本不会评估右侧表达式.

如果左边的表达式评估为Truthy,那么将评估右侧的表达式,结果将按原样返回.例如

console.log(1 && 2);
# 2
console.log(0 && 2);
# 0
Run Code Online (Sandbox Code Playgroud)

它首先进行评估1,它是Truthy所以它2被评估并返回值.这就是它打印的原因2.

在第二种情况下,0被评估为Falsy.所以,它会立即返回.这就是它打印的原因0.

一样的方法

console.log("John" && "Johny");
# Johny
Run Code Online (Sandbox Code Playgroud)

John将被评估为Truthy,因此Johny也将被评估和返回.这就是我们得到的原因Johny.

根据ECMA 5.1标准,将根据下表确定对象的真实性

+-----------------------------------------------------------------------+
| Argument Type | Result                                                |
|:--------------|------------------------------------------------------:|
| Undefined     | false                                                 |
|---------------|-------------------------------------------------------|
| Null          | false                                                 |
|---------------|-------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number        | The result is false if the argument is +0, ?0, or NaN;|
|               | otherwise the result is true.                         |
|---------------|-------------------------------------------------------|
| String        | The result is false if the argument is the empty      |
|               | String (its length is zero); otherwise the result is  |
|               | true.                                                 |
|---------------|-------------------------------------------------------|
| Object        | true                                                  |
+-----------------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

注意:最后一行,Object包括对象和数组.