简体   繁体   English

为什么JavaScript为“逻辑AND”运算返回空字符串?

[英]Why JavaScript returns empty string for “logical AND” operation?

Why do logical AND comparison between an empty string and false boolean returns an empty string? 为什么在空字符串和假布尔值之间进行逻辑AND比较会返回一个空字符串? and why do logical AND comparison between a string and false boolean returns false? 以及为什么字符串和false布尔值之间的逻辑与比较返回false?

Example: 例:

'' && true; --> returns ''
'string' && true --> returns true;
'' && false --> returns ''
'string' && false --> returns false;

Question is why javascript behaves this way? 问题是为什么javascript会表现这种方式?

Javascript AND( expr1 && expr2 ) operator works by returning the expressions based on the logic: JavaScript AND( expr1 && expr2 )运算符的工作原理是根据逻辑返回表达式:

if expr1 is falsy
  return expr1
else
  return expr2

Falsy values include your empty string( '' ), null , NaN , undefined , etc. You can read more about it at https://developer.mozilla.org/en-US/docs/Glossary/Falsy . Falsy值包括你的空字符串( '' ), nullNaNundefined ,等等。你可以阅读更多关于它https://developer.mozilla.org/en-US/docs/Glossary/Falsy

Also for more info on boolean operators, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators . 有关布尔运算符的更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

The && operator works very simply: if the first value is falsy, it returns the first value, otherwise it returns the second value. &&运算符的工作非常简单:如果第一个值是伪造的,则返回第一个值,否则返回第二个值。

The empty string '' is falsy, so '' && x returns '' for all x . 空字符串''是虚假的,因此'' && x对于所有x返回'' On the other hand, 'string' is truthy, so 'string' && x returns x for all x . 另一方面, 'string'是真实的,因此'string' && x x对于所有x返回x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM