javascript if 语句中的布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15393935/
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-10-27 00:37:59  来源:igfitidea点击:

boolean in an if statement

javascriptsemantics

提问by DirkZz

Today I've gotten a remark about code considering the way I check whether a variable is true or false in a school assignment.

今天我得到了一个关于代码的评论,考虑到我在学校作业中检查变量是真还是假的方式。

The code which I had written was something like this:

我写的代码是这样的:

var booleanValue = true;

function someFunction(){
    if(booleanValue === true){
        return "something";
    }
}

They said it was better/neater to write it like this:

他们说这样写更好/更整洁:

var booleanValue = true;

function someFunction(){
    if(booleanValue){
        return "something";
    }
}

The remark which I have gotten about the "=== true" part was that it was not needed and could create confusion.

我得到的关于“=== true”部分的评论是它不需要并且可能会造成混淆。

However my idea is that it is better to check whether the variable is a boolean or not, especially since Javascript is a loosetyped language.

但是我的想法是最好检查变量是否是布尔值,特别是因为 Javascript 是一种松散类型的语言。

In the second example a string would also return "something";

在第二个例子中,字符串也会返回“something”;

So my question; Is it neater to loose the "=== true" part in the future, or is it good practise to check the type of the variable as well.

所以我的问题; 将来松开“=== true”部分会更整洁,还是检查变量的类型也是一种好习惯。

Edit:In my "real" code the boolean represents whether an image has been deleted or not, so the only values boolValue should ever have is true or false.

编辑:在我的“真实”代码中,布尔值表示图像是否已被删除,因此 boolValue 应该具有的唯一值是 true 或 false。

0 and 1 for example shouldn't be in that variable.

例如 0 和 1 不应该在那个变量中。

回答by jfriend00

First off, the facts:

首先,事实:

if (booleanValue)

Will satisfy the ifstatement for any truthy value of booleanValueincluding true, any non-zero number, any non-empty string value, any object or array reference, etc...

将满足if语句的任何truthy值booleanValue包括true,任何非零数量,任何非空字符串值,任何物体或阵列基准,等...

On the other hand:

另一方面:

if (booleanValue === true)

This will only satisfy the ifcondition if booleanValueis exactly equal to true. No other truthy value will satisfy it.

这将仅满足if条件如果booleanValue完全等于true。没有其他真实值可以满足它。

On the other hand if you do this:

另一方面,如果你这样做:

if (someVar == true)

Then, what Javascript will do is type coerce trueto match the type of someVarand then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid ==because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid ==entirely.

然后,Javascript 要做的是强制类型true匹配someVar,然后比较两个变量的类型。在很多情况下,这可能不是人们想要的。正因为如此,在大多数情况下,你想要避免,==因为关于 Javascript 如何将两个东西强制为相同类型的规则有相当长的一套,除非你理解所有这些规则并且可以预测 JS 解释器可能会做的一切给定两种不同的类型(大多数 JS 开发人员不能),您可能希望==完全避免。

As an example of how confusing it can be:

作为一个例子,说明它有多混乱:

var x;

x = 0;
console.log(x == true);   // false, as expected
console.log(x == false);  // true as expected

x = 1;
console.log(x == true);   // true, as expected
console.log(x == false);  // false as expected

x = 2;
console.log(x == true);   // false, ??
console.log(x == false);  // false 

For the value 2, you would think that 2is a truthy value so it would compare favorably to true, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting trueto the number 1so it's comparing 2 == 1which is certainly not what you likely intended.

对于 value 2,您会认为这2是一个真实值,因此它会与 相比更有利true,但这不是类型强制的工作方式。它正在转换右手值以匹配左手值的类型,因此将其转换true为数字,1以便进行比较2 == 1,这肯定不是您想要的。

So, buyer beware. It's likely best to avoid ==in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.

所以,买家要小心。==在几乎所有情况下最好避免,除非您明确知道要比较的类型并知道所有可能的类型强制算法如何工作。



So, it really depends upon the expected values for booleanValueand how you want the code to work. If you know in advance that it's only ever going to have a trueor falsevalue, then comparing it explicitly with

因此,这实际上取决于booleanValue代码的预期值以及您希望代码如何工作。如果您事先知道它只会有 a trueorfalse值,那么将它明确地与

if (booleanValue === true)

is just extra code and unnecessary and

只是额外的代码和不必要的

if (booleanValue)

is more compact and arguably cleaner/better.

更紧凑,可以说更清洁/更好。

If, on the other hand, you don't know what booleanValuemight be and you want to test if it is truly set to truewith no other automatic type conversions allowed, then

另一方面,如果您不知道booleanValue可能是什么并且您想测试它是否真的设置为true并且不允许其他自动类型转换,那么

if (booleanValue === true)

is not only a good idea, but required.

不仅是个好主意,而且是必需的。



For example, if you look at the implementation of .on()in jQuery, it has an optional return value. If the callback returns false, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if falsewas returned, they check the return value explicity for === falsebecause they don't want undefinedor 0or ""or anything else that will automatically type-convert to false to also satisfy the comparison.

例如,如果您查看.on()jQuery中的实现,它有一个可选的返回值。如果回调返回false,则 jQuery 将自动停止事件的传播。在这种特定情况下,由于 jQuery 只希望false在返回时停止传播,因此他们明确地检查返回值,=== false因为他们不想要undefinedor0""或其他任何会自动将类型转换为 false 以满足比较的东西。

For example, here's the jQuery event handling callback code:

例如,这里是 jQuery 事件处理回调代码:

ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );

if ( ret !== undefined ) {
     event.result = ret;
     if ( ret === false ) {
         event.preventDefault();
         event.stopPropagation();
     }
 }

You can see that jQuery is explicitly looking for ret === false.

您可以看到 jQuery 明确地寻找ret === false.

But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:

但是,考虑到代码的需要,jQuery 代码中还有许多其他地方可以进行更简单的检查。例如:

// The DOM ready check for Internet Explorer
function doScrollCheck() {
    if ( jQuery.isReady ) {
        return;
    }
    ...

回答by karaxuna

If you write: if(x === true), It will be true for only x = true

如果你写:if(x === true),它只对 x = true 成立

If you write: if(x), it will be true for any xthat is not: '' (empty string), false, null, undefined, 0, NaN.

如果你写: if(x),那么对于任何不是:''(空字符串)、false、null、undefined、0、NaN 的x都为真。

回答by QuentinUK

In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-

在普通的“if”中,变量将被强制为布尔值,并在对象上使用 toBoolean:-

    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.

But comparison with === does not have any type coercion, so they must be equal without coercion.

但是与 === 的比较没有任何类型强制,因此它们必须是相等的,没有强制。

If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.

如果您说对象甚至可能不是布尔值,那么您可能需要考虑的不仅仅是真/假。

if(x===true){
...
} else if(x===false){
....
} else {
....
}

回答by Ven

It depends on your usecase. It may make sense to check the type too, but if it's just a flag, it does not.

这取决于您的用例。检查类型也可能有意义,但如果它只是一个标志,则不会。

回答by SLaks

In general, it is cleaner and simpler to omit the === true.

一般来说,省略=== true.

However, in Javascript, those statements are different.

但是,在 Javascript 中,这些语句是不同的。

if (booleanValue)will execute if booleanValueis truthy– anything other than 0, false, '', NaN, null, and undefined.

if (booleanValue)如果将执行booleanValuetruthy-比其他任何东西0false''NaNnull,和undefined

if (booleanValue === true)will only execute if booleanValueis precisely equal to true.

if (booleanValue === true)仅当booleanValue恰好等于时才会执行true

回答by Apollo SOFTWARE

The identity (===)operator behaves identically to the equality (==)operator except no type conversion is done, and the types must be the same to be considered equal.

除了不进行类型转换外,恒等(===)运算符的行为与相等(==)运算符相同,并且类型必须相同才能被视为相等。

回答by Alyafey

Since the checked value is Booleanit's preferred to use it directly for less coding and at all it did same ==true

由于检查值是Boolean首选直接使用它以减少编码,并且它完全相同==true

回答by Sunny

Since you already initialized clearly as bool, I think ===operator is not required.

由于您已经清楚地初始化为 bool,因此我认为===不需要运算符。

回答by Barmar

If the variable can only ever take on boolean values, then it's reasonable to use the shorter syntax.

如果变量只能采用布尔值,那么使用较短的语法是合理的。

If it can potentially be assigned other types, and you need to distinguish truefrom 1or "foo", then you must use === true.

如果它可能被分配其他类型,并且需要区分true来自1或者"foo",则必须使用=== true

回答by Jesse Hallett

I think that your reasoning is sound. But in practice I have found that it is far more common to omit the ===comparison. I think that there are three reasons for that:

我认为你的推理是合理的。但在实践中,我发现省略===比较更为常见。我认为有以下三个原因:

  1. It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
  2. Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected undefinedor nullvalue. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
  3. JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.
  1. 它通常不会增加表达式的含义 - 在已知值是布尔值的情况下。
  2. 因为 JavaScript 中有大量的类型不确定性,所以当你得到一个意想不到的undefinednull值时,强制类型检查往往会咬你。通常,您只是希望您的测试在这种情况下失败。(虽然我试图用“快速失败”的座右铭来平衡这个观点)。
  3. JavaScript 程序员喜欢快速而宽松地使用类型——尤其是在布尔表达式中——因为我们可以。

Consider this example:

考虑这个例子:

var someString = getInput();
var normalized = someString && trim(someString);  
// trim() removes leading and trailing whitespace

if (normalized) {
    submitInput(normalized);
}

I think that this kind of code is not uncommon. It handles cases where getInput()returns undefined, null, or an empty string. Due to the two boolean evaluations submitInput()is only called if the given input is a string that contains non-whitespace characters.

我认为这种代码并不少见。它处理情况getInput()回报undefinednull或一个空字符串。由于两个布尔值submitInput()仅在给定的输入是包含非空白字符的字符串时才调用。

In JavaScript &&returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalizedwill be undefinedif someStringwas undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.

在 JavaScript 中,&&如果第一个参数为真则返回其第一个参数,如果第一个参数为真则返回第二个参数;所以normalizedundefined,如果someString是不确定的,等等。这意味着上面布尔表达式的所有输入实际上都不是布尔值。

I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for nullor undefinedvalues, which would clutter up the code. In JavaScript that is not needed.

我知道很多习惯于强类型检查的程序员在看到这样的代码时会畏缩。但请注意,应用强类型可能需要对nullundefined值进行显式检查,这会使代码变得混乱。在 JavaScript 中不需要。