54

Which is the better way for conditional variable assignment?

1st method

 if (true) {
   var myVariable = 'True';
 } else {
   var myVariable = 'False';
 }

2nd Method

 var myVariable = 'False';
 if (true) {
   myVariable = 'True';
 }

I actually prefer 2nd one without any specific technical reason. What do you guys think?

4

12 回答 12

113

try this

var myVariable = (true condition) ? "true" : "false"
于 2012-06-07T06:45:28.730 回答
28

我知道有两种方法可以通过条件声明变量的值。

方法 1:如果条件评估为真,则将列左侧的值分配给变量。如果条件评估为假,则右侧的条件将分配给变量。您还可以将许多条件嵌套到一个语句中。

var a = (true)? "true" : "false";

方法 1 的嵌套示例:将变量 A 的值更改为 0、1、2 和负值,以查看语句将如何产生结果。

var a = 1;
var b = a > 0? (a === 1? "A is 1" : "A is not 1") : (a === 0? "A is zero" : "A is negative");

方法二:在这个方法中,如果||的左边的值 等于零、假、空、未定义或空字符串,则右侧的值将分配给变量。如果 || 左边的值 不等于 0、false、null undefined 或空字符串,则左侧的值将赋给变量。

虽然左边的值可以是一个未定义的值,供 JS 评估条件,但必须声明变量,否则会产生异常。

var a = 0;
var b = a || "Another value";
于 2017-03-19T11:03:48.160 回答
11

另一种方法是利用逻辑运算符返回值的能力。

let isAnimal = false;
let isPlant = true;

let thing = isAnimal && 'animal' || isPlant && 'plant' || 'something else';

console.log(thing);

在上面的代码中,当其中一个标志为 trueisAnimalisPlant时,将返回它旁边的字符串。这是因为两者&&||导致它们的操作数之一的值:

  • 如果 A 可以强制为 false,则 A && B 返回值 A;否则,它返回 B。
  • 一个 || 如果 A 可以强制为真,则 B 返回值 A;否则,它返回 B。

受本文启发的答案:https ://mariusschulz.com/blog/the-and-and-or-operators-in-javascript

PS:仅供学习之用。在您的生产代码中使用此方法不会使您和您的同事的生活更加艰难。

于 2020-02-27T15:58:08.020 回答
10

You could do a ternary, which is a lot shorter (and no darn curly braces):

var myVariable = (true) ? 'True' : 'False';
于 2012-06-07T06:44:54.750 回答
7

另一个很酷的事情是,您可以根据条件进行多项分配:

let [long_str, short_str] = a.length > b.length ? [a, b] : [b, a]
于 2018-11-06T17:31:21.383 回答
6

当您在变量中仅存储真假时的第三种方式,然后使用

 var myVariable =(condition_written_in_if);
于 2012-06-07T06:46:15.900 回答
5

为了完成,除了这里提到的所有其他方法之外,还有另一种方法,即使用查找表。

假设您有许多可能的值,您可以以声明方式配置 Map 而不是使用if, switchorternary语句。

Object map = {
   key1: 'value1',
   key2: 'value2,
   keyX: 'valueX'
};

var myVariable = map[myInput];

这甚至适用于布尔值:

Object map = { true: 'value1', false: 'value2 };

var myVariable = map[myBoolean];

对于布尔值,尽管使用专门为此设计的逻辑运算符,但您可能会以“正常”方式进行操作。虽然有时它可能很有用,例如:

  • 便携性:您可以传递地图
  • 可配置性:可能值来自属性文件
  • 可读性:如果您不在乎它是否为布尔值,您只想避免条件逻辑并以这种方式减少认知负担

请注意,使用查找映射的优势与使用函数变量(闭包)的优势之间存在一些重叠。

于 2019-10-19T11:24:40.337 回答
4

The first solution uses only one assignment instead of 1,5 by average in the second code snippet. On the other hand the first code snippet is less readable as people not familiar with JavaScript might not realize that the scope of a variable is not block oriented by function oriented - on other languages with C-like syntax myVariable would not be accessible outside if and else blocks.

In other words both solutions have disadvantages. What about ternary operator:

var myVariable = condition? 'True' : 'False';

or if you don't care about the camel-case (although I understand this is just an example, not a real code);

var myVariable = (!!condition).toString();
于 2012-06-07T06:44:46.870 回答
1

如果您厌倦了三元运算符,请使用 IIFE

另一种方法是使用Immediately Invoked Function Expression。它的好处是它可以容纳一些逻辑,并且可以从外界封装。

const direction = "n";

const directionFull= (() => {
    switch(direction ){
        case "n": return "north";
        case "s": return "south";
        case "w": return "west";
        case "e": return "east"; 
    }
})()

console.log(directionFull);

于 2021-09-12T01:06:16.287 回答
0

I would prefer 2nd option too, no technical reason but for the sake of easy to read code, readability is very important in code.

If you see the second option, from processing point of view only one check will ever be executed, saved some very minute processing time, so there is only one check in second case.

于 2012-06-07T06:44:03.687 回答
0

It depends on the use for me. If I have code that I only want to run if true, but with no extra code for false, I'll use the second. If I want to execute some code on true, and different on false, I use the first. It all depends on use, but the general rule for me is to write once. Keep it clean, keep it simple, and keep it short

于 2012-06-07T06:45:07.250 回答
0

也许您只需要&&运算符来检查布尔值是否为真,如果是,则将“myVariable”设置为真。

var myVariable = 'False';
true && myVariable = 'True';
于 2020-02-25T11:57:06.703 回答