简体   繁体   English

在javascript中使用三元运算符

[英]use of ternary operator in javascript

I know basic use of '?' 我知道'?'的基本用法 ternary operator. 三元运算符。 window.URL should be expression, which should return true or false. window.URL应该是表达式,应返回true或false。 But in this case, it is returning a string. 但是在这种情况下,它将返回一个字符串。

how this expression is evaluated. 如何评估此表达式。

var createSrc = window.URL ? window.URL.createObjectURL : function(stream) {return stream;};

A string is evaluated to true as long it is not empty, in which case it is false . 只要字符串不为空,就将其评估为true ,在这种情况下为false

Though it doesn't look like window.URL is a string in this case. 尽管它看起来不像window.URL在这种情况下是一个字符串。 It appears to be an object, which if undefined will evaluate to false as well. 它似乎是一个对象,如果undefined ,其结果也将为false

What your statement does, is it checks if window.URL exists. 您的语句所做的是检查window.URL存在。 If it does, then it will assign to createSrc , the value of window.URL.createObjectURL , which I assume is probably a function. 如果是这样,那么它会分配给createSrc ,价值window.URL.createObjectURL ,我以为可能是一个功能。 Otherwise, it will assign the third part of the ternary operator, function(stream) {return stream;} . 否则,它将分配三元运算符的第三部分function(stream) {return stream;}

This means, createSrc should always be a function and calling it will not generate an error. 这意味着createSrc应该始终是一个函数,并且调用它不会产生错误。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM