【问题标题】:Javascript short circuiting in if statementif语句中的Javascript短路
【发布时间】:2017-08-23 20:06:28
【问题描述】:

我对下面的 if 语句代码感到困惑。不确定它到底在做什么

if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}

有人可以帮我理解吗?

if 语句是否短路: 即

1- 如果左侧的第一个 this.props.filterURL 为假,那么它将返回假。 2- 如果第一个 this.props.filterURL 有一个值,那么它将返回 true,并且第二个变量 nextProps.filterURL 将与语句最右侧的 this.props.filterURL 进行比较?

【问题讨论】:

  • 你说的是对的。首先它检查 this.props.filterURL 的值是否为真。如果失败,则返回 false,如果为 true,则仅检查条件 nextProps.filterURL !== this.props.filterURL
  • 你总结的很准确。表达式的左操作数为假会使整个表达式为假,这一事实确实是短路的。
  • 如果 this.props.filterUrl 是真的,它将继续检查是否不等于 nextProps.filterUrl,如果整个事情都是真的,那么执行封闭的代码。
  • 请注意,第一个 this.props.filterURL 正在检查 truthy 值,而不是专门检查 true。如果未定义 falsy 的属性,但如果值为 null0 或空字符串,则它们也都是假的。
  • 这在 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 等地方都有很好的记录,在 SO 上也有很多帖子。在控制台或沙箱/REPL 中验证也非常容易。

标签: javascript if-statement short-circuiting


【解决方案1】:

注意事项:

  • 这种短路有利于性能,因为它允许跳过大量计算。
  • AND 运算符 (&&) 如果两个表达式都为真,则返回真,否则返回假。

演示

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.

【讨论】:

    【解决方案2】:

    在 AND 运算符的情况下,仅当第一个表达式为真时才计算第二个表达式。

    在你的情况下,

    if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
    

    可以解释为if(expr1 &amp;&amp; expr2) 其中expr1= this.props.filterURLexpr2 = nextProps.filterURL !== this.props.filterURL

    对于第一个表达式expr1,它会评估它是否不是null 或undefined...

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

    【讨论】:

    • 仅当第一个为真时这是不正确的。 评估它是否不为空或未定义。这也是不正确的。
    • 在浏览器 JS 控制台中请运行下面的代码并查看 O/P 是什么,然后将 number 设置为 null 或 undefined 并单独运行 if 块... var number ="number"; if(number) { console.log("hello"); }
    猜你喜欢
    • 2021-08-20
    • 2013-02-15
    • 2016-03-26
    • 1970-01-01
    • 2011-06-30
    • 2012-09-12
    • 2019-10-18
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多