简体   繁体   English

Javascript:奇怪的行为“空字符串”和“假”返回空字符串

[英]Javascript : Strange behaviour `empty string` AND `false` returns empty string

Today I came across the strange behaviour in Javascript. 今天,我遇到了Javascript中的奇怪行为。 Below is the code 下面是代码

return "" && false

returns "". 返回“”。

Why it behaves so ? 为什么会这样呢?

Because 因为

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows: 产生LogicalANDExpression:LogicalANDExpression && BitwiseORExpression的评估如下:

  1. Let lref be the result of evaluating LogicalANDExpression. 令lref为评估LogicalANDExpression的结果。
  2. Let lval be GetValue(lref). 令lval为GetValue(lref)。
  3. If ToBoolean(lval) is false, return lval. 如果ToBoolean(lval)为false,则返回lval。
  4. Let rref be the result of evaluating BitwiseORExpression. 令rref为评估BitwiseORExpression的结果。
  5. Return GetValue(rref). 返回GetValue(rref)。

ECMAScript 5.1 ECMAScript 5.1

This means: 这意味着:

Return the first value if it is falsy, return the second value if the first is truthy. 如果第一个值是假,则返回第一个值;如果第一个值是真,则返回第二个值。


This is also the behavior seen if you do: 这也是您执行以下操作时看到的行为:

return false && true

You get false . false

This means also that this 这也意味着

return 23 && "Hello"

would give you "Hello" 会给你“你好”

LHS首先运行,返回使您退出该函数

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

相关问题 字符串比较返回false。 使用jQuery mobile的奇怪的javascript行为 - String comparison returns false. Strange javascript behaviour with jQuery mobile 在javascript中,空字符串作为布尔值总是假的吗? - In javascript, is an empty string always false as a boolean? 空字符串在 Javascript 中计算为 false 的原因是什么 - What is the reason that an empty string evaluates to false in Javascript 空字符串应为“ false” - Empty string should be 'false' jQuery:创建一个名为“ containsBlanks”的javascript方法,如果任何带有“必需”类的输入都包含空字符串,则返回true,否则返回false - Jquery: create a javascript method called 'containsBlanks' that returns true if any inputs with class 'required' has an empty string in, false if not 为什么JavaScript为“逻辑AND”运算返回空字符串? - Why JavaScript returns empty string for “logical AND” operation? JavaScript 条件语句检查空返回字符串 - JavaScript conditional statement with check for empty returns string 抓取JavaScript网址,但Selenium返回空字符串 - scraping javascript url but selenium returns empty string 解密返回空字符串 - Decryption returns empty string Handlebars 返回空字符串 - Handlebars returns empty string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM