[英]Is there a JavaScript equivalent to PHP's “or” operator?
在PHP中,如果第一个表达式的计算结果为false,则可以使用“ 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>
有一个更好的方法吗?
(1 == 2) || alert("error: 1 does not equal 2");
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)|| “错误:1不等于2”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.