gpt4 book ai didi

JavaScript 类型转换 : (true && 1) vs (true | | 1)

转载 作者:可可西里 更新时间:2023-11-01 01:22:54 24 4
gpt4 key购买 nike

JavaScript 是非严格类型的语言,例如 Java。

正如我们所知,它根据上下文转换结果值:

"2"+ "3" 结果 "23"

"2"* "3" 结果 6

这很清楚,可以理解。

我只是尝试了以下表达式并感到困惑:

true && 1 结果 1
真|| 1 结果 true

为什么第一个给出 Number 而第二个给出 boolean?

考虑到 JavaScript 转换规则,由于表达式的 boolean 上下文,我希望在这两种情况下都能得到 boolean 值。

最佳答案

检查 Douglas Crockford's site ,它说:

The && operator is commonly called logical and. It can also be called guard. If the first operand is false, null, undefined, "" (the empty string), or the number 0 then it returns the first operand. Otherwise, it returns the second operand. This provides a convenient way to write a null-check:

var value = p && p.name; /* The name value will only be retrieved from
p if p has a value, avoiding an error. */

The || operator is commonly called logical or. It can also be called default. If the first operand is false, null, undefined, "" (the empty string), or the number 0, then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values:

value = v || 10; /* Use the value of v, but if v doesn't have a value,
use 10 instead. */

关于JavaScript 类型转换 : (true && 1) vs (true | | 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8559920/

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