我对以下if语句代码感到困惑。不确定它到底在做什么
if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
有人可以帮我理解这个吗?
if语句是否短路: 即
1-如果从左侧首先this.props.filterURL为false,则返回false。 2-如果首先this.props.filterURL有一个值,那么它将返回true,第二个变量nextProps.filterURL将在最右边的语句中与this.props.filterURL进行比较?
答案 0 :(得分:1)
注意:
(&&)
如果两个表达式都为true则返回true,否则返回false。<强>样本强>
var x = 1;
var y = 5;
if (x > 0 && y < 6) { console.log(x) }; // true
if(x > 1 && y < 6) { console.log(x) }; // false
the first this.props.filterURL is checking for a truthy value, not for true specifically. If the property is not defined that is falsy, but if the value is null or 0 or an empty string those are all falsy too.
答案 1 :(得分:0)
如果是AND运算符,它仅在第一个表达式为真时才计算第二个表达式。
在你的情况下,
if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
可以解释为if(expr1 && expr2)
其中expr1= this.props.filterURL
和expr2 = nextProps.filterURL !== this.props.filterURL
对于第一个表达式expr1
,它会判断它是否 null或未定义 ...
表示第二个表达式expr2
nextProps.filterURL!== this.props.filterURL 它会检查值和数据类型。因此,例如,如果您将两个值都设置为相同的1234但是对于一个它是String类型而另一个它是数字,则此条件为真。