Javascript - If 语句 - 条件中的字符串&&布尔值

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

Javascript - If statement - string && boolean in condition

javascript

提问by Justin

If I am testing a boolean by itself I know I don't have to put == true.

如果我自己测试一个布尔值,我知道我不必输入 == true。

 if (bool) {
   foo();
 }

I have an if condition that tests for the truthfulness of both a sting's value and a boolean, can I replace:

我有一个 if 条件来测试 sting 值和布尔值的真实性,我可以替换:

 if ( string === "hello" && bool == true ) {
   foo();
 }

with:

和:

 if ( string === "hello" && bool ) { 
 foo();
 }

?

?

Also, would a bool value ever use a triple equal sign? So far what I've seen on bool tests are double equals only.

此外,布尔值是否会使用三重等号?到目前为止,我在 bool 测试中看到的只是双重等于。

Thanks.

谢谢。

回答by contactmatt

Use the triple equal sign, it's preferred.

使用三重等号,它是首选

if(bool == true), if(bool === true) and if(bool)are all different expressions. The first is saying that the value bool must be of the primitive JavaScript type true, or the object representation of the Boolean (i.e. new Boolean()) object with a value of true. The second is saying that the value "bool" mustbe of the primitive type bool(the new Boolean() object, even with a value of true, will fail). The third expression is only false if bool is

if(bool == true),if(bool === true) and if(bool)都是不同的表达方式。第一个是说 bool 值必须是原始 JavaScript 类型 true,或值为 true 的 Boolean(即 new Boolean())对象的对象表示。第二个是说值“bool”必须原始类型 bool(新的 Boolean() 对象,即使值为 true,也会失败)。只有当 bool 为时,第三个表达式才为假

  • false
  • null
  • undefined
  • empty string ''
  • The number 0
  • The number NaN
  • 错误的
  • 空值
  • 不明确的
  • 空字符串''
  • 数字 0
  • 数字 NaN

Meaning, the second expression will evalauate to true if you pass in an empty object ({}), for example.

这意味着,例如,如果您传入一个空对象 ({}),则第二个表达式将评估为真。

Some Examples:

一些例子:

var bool = true;
var boolObj = new Boolean(true);
var boolEmptyObj = {};

if (bool === true) { alert("This will alert"); }
if (boolObj === true) { alert("Nope, this wont alert"); }
if (boolEmptyObj) { alert("This will alert"); }

回答by MattDiamant

Yes. If bool is truly a boolean, it will evaluate to true or false, just the same as any expression would. You can also make sure that bool is boolean by using:

是的。如果 bool 是真正的布尔值,它将评估为真或假,就像任何表达式一样。您还可以使用以下方法确保 bool 是布尔值:

!!bool

回答by Jefferson Henrique C. Soares

Yes, but when you use only boolthe value is falsefor these values: null, undefined, 0and "" (empty string). You need to be careful.

是的,但是当你只使用bool值是false这些值:nullundefined0"" (empty string)。你需要小心。