gpt4 book ai didi

javascript - 为什么这段代码在 JavaScript 中会产生 3?

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:10 25 4
gpt4 key购买 nike

为什么下面的代码会产生a == 3

var x = "abc";
var y = 3;
var z = "xyz";
var a = x && y || z;

http://jsfiddle.net/thinkingmedia/qBZAL/

我原以为这会导致 a == true

为什么逻辑运算符将 "abc" 评估为 true 但不将 3 评估为 true .相反,它会生成 3 作为结果。

此外,如果您更改 y = 0,则 a == "xyz" 这意味着 && 处理 0false。将数字视为数字会怎样?

这里的逻辑运算符是怎么回事?

最佳答案

这是意料之中的。

在 JavaScript(和许多其他语言)中,不仅 bool 值本身是真或假,其他对象也可以是真或假(参见 the docs on mdn):

The value […] is converted to a boolean value, if necessary. If value is […] is 0, -0, null, false, NaN, undefined, or the empty string (""), [it is] false. All other values, including any object or the string "false", create […] true.

逻辑运算符 ||&& 不返回 truefalse,而是返回影响它们是真还是假的最后一个参数(reference):

  • expr1 && expr2 – Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
  • expr1 || expr2 – Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

关于javascript - 为什么这段代码在 JavaScript 中会产生 3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23277122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com