【问题标题】:Is there a JavaScript equivalent to PHP's "or" operator?是否有等效于 PHP 的“或”运算符的 JavaScript?
【发布时间】:2018-12-29 06:40:30
【问题描述】:

在 PHP 中,如果第一个表达式的计算结果为假,您可以使用“或”关键字来执行函数:

<?php
(1 == 2) or exit("error: 1 does not equal 2");
?>

在 JavaScript 中是否有类似 PHP 示例的单行代码?

在 JavaScript 中我能想到的最好的方法是辅助函数,其中参数 1 是要评估的条件,参数 2 是字符串或函数。如果参数 1 为假且参数 2 为字符串,则函数将抛出错误,并将字符串作为错误消息。如果参数 2 是一个函数,则该函数将被执行:

<script>
function or(condition, err_msg_or_function) {
    if (typeof (condition) !== "boolean") {
        throw new Error("or error: argument 1 must be boolean");
    } else {
        if (!condition) {
            if (typeof (err_msg_or_function) === "function") {
                err_msg_or_function();
            } else if (typeof (err_msg_or_function) === "string") {
                throw new Error(err_msg_or_function);
            } else {
                throw new Error("or error: argument 2 must be a function or a string");
            }
        }
    }
}
</script>

在实践中:

<script>
or((1 == 2), "error: 1 does not equal 2");
</script>

有没有更好的方法来做到这一点?

【问题讨论】:

  • true === false || console.log('something like that?')
  • @Jeto roblox oof

标签: javascript php syntactic-sugar


【解决方案1】:
(1 == 2) || alert("error: 1 does not equal 2");

【讨论】:

  • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
【解决方案2】:
【解决方案3】:
false === true || document.write('By using this we can perform the same thing with PHP')



(1===1) === (2===2) || document.write('we can replace the booleans by operators')

如果你正在寻找类似的东西,试试这个......

【讨论】:

    【解决方案4】:

    某事||另一个

    (1 == 2) || “错误:1 不等于 2”

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 2014-01-24
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      相关资源
      最近更新 更多