Javascript 条件变量赋值的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10926853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:35:54  来源:igfitidea点击:

Best Way for Conditional Variable Assignment

javascript

提问by RaviTeja

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?

我实际上更喜欢没有任何特定技术原因的第二个。你们有什么感想?

回答by dku.rajkumar

try this

尝试这个

var myVariable = (true condition) ? "true" : "false"

回答by Kevin Ng

There are two methods I know of that you can declare a variable's value by conditions.

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

Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into one statement.

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

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

Nesting example of method 1: Change variable A value to 0, 1, 2 and a negative value to see how the statement would produce the result.

方法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");

Method 2: In this method, if the value of the left of the || is equal to zero, false, null, undefined, or an empty string, then the value on the right will be assigned to the variable. If the value on the left of the || does not equal to zero, false, null undefined, or an empty string, then the value on the left will be assigned to the variable.

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

Although the value on the left can be an undefined value for JS to evaluate the condition but the variable has to be declared otherwise an exception will be produced.

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

var a = 0;
var b = a || "Another value";

回答by Joseph

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

你可以做一个三元,它要短得多(而且没有花括号):

var myVariable = (true) ? 'True' : 'False';

回答by Joseph

Third way when you are storing only true false in variabel then use

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

 var myVariable =(condition_written_in_if);

回答by aris

Another cool thing is that you can do multiple assignment based on a conditional:

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

let [long_str, short_str] = a.length > b.length ? [a, b] : [b, a]

回答by Tomasz Nurkiewicz

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 myVariablewould not be accessible outside ifand elseblocks.

第一个解决方案仅使用一个赋值,而不是第二个代码片段中的平均 1,5。另一方面,第一个代码片段的可读性较差,因为不熟悉 JavaScript 的人可能没有意识到变量的作用域不是面向函数的面向块的——在其他具有类似 C 语法的语言上,myVariable在外部ifelse块中是无法访问的。

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();

回答by Benny Bottema

Just for completion, there is another way in addition to all the others mentioned here, which is to use a lookup table.

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

Say you have many possible values, you could declaratively configure a Map instead of using an if, switchor ternarystatement.

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

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

var myVariable = map[myInput];

This works even for booleans:

这甚至适用于布尔值:

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

var myVariable = map[myBoolean];

For booleans you would probably do it the 'normal' way though with logic operators specifically designed for that. Though sometimes it can be useful, such as:

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

  • portability: you can pass a map around
  • configurability: maybe the values come from a property file
  • readability: if you don't care it's a boolean or not, you just want to avoid conditional logic and reduce cognitive load that way
  • 便携性:你可以传递地图
  • 可配置性:也许值来自属性文件
  • 可读性:如果您不在乎它是否是布尔值,您只想避免条件逻辑并以这种方式减少认知负荷

Note there is some overlap between the advantages using a lookup map and advantages of using a function variable (closure).

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

回答by Eric Valero

Maybe you simply need &&operator to check if boolean is true, if it is, assing "myVariable" to true.

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

var myVariable = 'False';
true && myVariable = 'True';

回答by Valentin

An alternative way of doing this is by leveraging the ability of logical operators to return a value.

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

let isAnimal = false;
let isPlant = true;

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

console.log(thing);

In the code above when one of the flags is true isAnimalor isPlant, the string next to it is returned. This is because both &&and ||result in the value of one of their operands:

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

  • A && B returns the value A if A can be coerced into false; otherwise, it returns B.
  • A || B returns the value A if A can be coerced into true; otherwise, it returns B.
  • 如果 A 可以被强制为 false,则 A && B 返回值 A;否则返回 B。
  • 一个|| 如果 A 可以被强制为真,则 B 返回值 A;否则返回 B。

Answer inspired by this article: https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript

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

PS: Should be used for learning purposes only. Don't make life harder for you and your coworkers by using this method in your production code.

PS:仅供学习使用。不要在您的生产代码中使用这种方法,让您和您的同事生活更艰难。

回答by Gareth Parker

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

这取决于我的用途。如果我有我只想在 true 时运行的代码,但没有额外的 false 代码,我将使用第二个。如果我想在 true 上执行一些代码,而在 false 上不同,我使用第一个。这一切都取决于使用,但对我来说一般的规则是写一次。保持干净,保持简单,保持简短