gpt4 book ai didi

Javascript ||运算符(operator)

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

我正在使用大型 JS 库在 Canvas 中执行某些绘图操作。查看库代码(进行适应性更改),我遇到了“||”运算符的使用方式当然不应评估为 bool 值。这是否意味着这是一个不同的运算符(operator),还是我遗漏了一些明显的东西?示例如下:

var $time = Date.now || function(){
return +new Date;
};

最佳答案

已经有一个公认的答案,但我想提一下,OR-Operator 也称为 Default-Operator,因为它不返回 bool 值,而是返回左手或右手参数。

AND 运算符也是如此,也称为守卫运算符。

查看 crockford's Survey of the JavaScript Programming Language了解更多详情:

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 ||运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1378619/

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