Javascript ||操作者 [英] Javascript || operator
问题描述
我正在使用一个大型JS库在canvas中执行某些绘图操作。检查库代码(以进行适应性更改),我遇到了以某种方式使用的||运算符,该方式当然不应该计算为布尔值。这是否意味着这是一个不同的运营商,还是我错过了一些明显的东西?示例如下:
I am using a large JS library to perform certain drawing operations in canvas. Reviewing the library code (to make accommodating changes), I have ran into the '||' operator being used in a fashion which certainly should not evaluate to Boolean. Does this mean that this is a different operator or am I missing something obvious? An example follows:
var $time = Date.now || function(){
return +new Date;
};
推荐答案
||
operator 计算到第一个操作数,如果可以的话转换为true或否则转换为最后一个操作数。所以在你的例子中, $ time
将是 Date.now
如果它存在或者声明的函数不存在。
The ||
operator evaluates to the first operand if it can be converted to true or the last operand otherwise. So in your example $time
will be Date.now
if it exists or the declared function otherwise.
这篇关于Javascript ||操作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!