是否有 JavaScript 等同于 PHP 的 "or" 运算符?

Is there a JavaScript equivalent to PHP's "or" operator?

在 PHP 中,如果第一个表达式的计算结果为错误,您可以使用 "or" 关键字来执行函数:

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

在 JavaScript 中是否有类似的东西,像 PHP 示例一样的甜美单行?

我在 JavaScript 中能想到的最好的方法是辅助函数,其中参数 1 是要计算的条件,参数 2 是字符串或函数。如果参数 1 为 false 且参数 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>

有更好的方法吗?

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')

如果您正在寻找这样的东西,请试试这个...

某事||另一个

(1 == 2) || "error: 1 does not equal 2"

你真的应该看看 Online Documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical

(1 == 2) || alert("error: 1 does not equal 2");