if语句中的Javascript短路

时间:2017-03-30 04:41:11

标签: javascript if-statement short-circuiting

我对以下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进行比较?

2 个答案:

答案 0 :(得分:1)

注意:

  • 这种短路有利于提高性能,因为它可以跳过大量的计算。
  • AND运算符 (&&) 如果两个表达式都为true则返回true,否则返回false。

enter image description here

<强>样本

var x = 1;
var y = 5;

if (x > 0 && y < 6) { console.log(x) }; // true

if(x > 1 && y < 6) { console.log(x) }; // false

  • 正如nnnnnn在其评论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.filterURLexpr2 = nextProps.filterURL !== this.props.filterURL

对于第一个表达式expr1,它会判断它是否 null或未定义 ...

表示第二个表达式expr2 nextProps.filterURL!== this.props.filterURL 它会检查值和数据类型。因此,例如,如果您将两个值都设置为相同的1234但是对于一个它是String类型而另一个它是数字,则此条件为真。