【问题标题】:how variables are set when using multiple OR (||) operators in Jquery/Javascript?在 Jquery/Javascript 中使用多个 OR (||) 运算符时如何设置变量?
【发布时间】:2012-09-10 08:08:11
【问题描述】:

我无法理解在 Jquery/Javascript 中执行 || 的顺序。

如果我有这个:

  someVar = $el.attr("one") || options.two || "three";

$el.attr("one")options.two 都未定义时,它将someVar 设置为“三”。

我需要在此语句中添加另一个条件,如下所示:

  someVar = $el.attr("one") || options.two || options.extra == "true" ? undefined : "three";

所以这应该说:

如果'$el.attr("one")''options.two'都没有定义,检查是否'options.extra == true',如果是,设置为'undefined',否则设置为'three'

但是,即使我设置了$el.attr("one"),我总是得到undefined,但我不明白为什么?

谁能告诉我我的逻辑有什么问题?

谢谢!

【问题讨论】:

  • 请注意,options.extra == "true" 仅在 options.extra 为假或恰好是字符串 true 时为真,这可能不是您想要的。

标签: javascript jquery operators operator-precedence


【解决方案1】:

我认为你必须加上一些括号:

someVar = $el.attr("one") || options.two || (options.extra == "true" ? undefined : "three");

实际上你自己的代码被读作:

someVar = ($el.attr("one") || options.two || options.extra == "true") ? undefined : "three";

【讨论】:

    【解决方案2】:

    原因是? : 的绑定比|| 弱,因此最后评估。这和你写的一样:

    ( $el.attr("one") || options.two || options.extra == "true" ) ? undefined : "three";
    

    这总是会产生未定义的,因为第一个表达式总是为真(因为你设置了$el.attr("one")

    这就是为什么你必须用括号来解决这个问题:

    $el.attr("one") || options.two || (options.extra == "true" ? undefined : "three");
    

    查看operator precedence table,在这种情况下它会派上用场。

    【讨论】:

    • 好的。谢谢你的解释。
    • @frequent 我添加了一个指向 javascript 运算符优先级表的链接,在这种情况下这是你最好的朋友;)
    【解决方案3】:

    只用逻辑运算符的写法是

      someVar = $el.attr("one") || options.two || options.extra != "true" && "three" || undefined;
    

    ...并不是说我会在实际代码中使用它。 (我可能也不会将逻辑运算符与条件运算符混合使用。)

    【讨论】:

    • 应该是options.extra == "true" && undefined || "three",因为&&具有更高的优先级。
    • 已修复。将 "three" 放在末尾是行不通的,因为具有真值的 OR 链是末尾永远不会给出假值,例如 undefined
    • 是的——这就是为什么你不应该将它用于条件变量赋值;)
    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2017-03-06
    相关资源
    最近更新 更多