如何避免JavaScript中的短路评估? [英] How to avoid short-circuited evaluation in JavaScript?

查看:218
本文介绍了如何避免JavaScript中的短路评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行&& 语句的两面,但如果第一部分返回 false 。示例:

I need to execute both sides of an && statement, but this won't happen if the first part returns false. Example:

function checkSomething(x) {
    var not1 = x !== 1;
    if (not1) doSomething(x);

    return not1;
}

function checkAll() {
    return checkSomething(1)
        && checkSomething(3)
        && checkSomething(6)
}

var result = checkAll();

这里的问题是 doSomething(x)应该执行两次,但因为 checkSomething(1)返回 false ,其他检查将不会被调用。 运行所有检查并返回结果的最简单方法是什么?

The problem here is that doSomething(x) should be executed twice, but because checkSomething(1) returns false, the other checks won't be called. What is the easiest way to run all the checks and return the result?

我知道我可以保存所有变量中的值并随后检查它们,但是当我进行大量检查时,这看起来并不是很干净。我正在寻找替代方案。

I know I could save all the values in variables and check those subsequently, but that does not look very clean when I have a lot of checks. I am looking for alternatives.

推荐答案

您可以将比较结果相乘并将其转换为布尔值。

You can multiply the comparison result and cast it to boolean.

function checkSomething(x) {
    var not1 = x !== 1;
    if (not1) alert(x);
    return not1;
}

function checkAll() {
    return !!(checkSomething(1) * checkSomething(2) * checkSomething(3));
}

document.write(checkAll());

或采取一些数组方法:

function checkAll() {
    return [checkSomething(2), checkSomething(2), checkSomething(3)].every(Boolean);
}

这篇关于如何避免JavaScript中的短路评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆