JavaScript短路评估错误

JavaScript short circuit evaluation error?

本文关键字:错误 评估 短路 JavaScript      更新时间:2023-09-26

下面的两个JS代码片段让我感到困惑,在我看来,由于短路评估,两者都应该工作相同。但由于某种原因,代码片段"1"导致错误(在第三行):

无法读取未定义的属性"匹配"

数组"a"包含用户输入的 3 个字符值。我希望代码在字符未定义、空字符串或字母或数字时返回 true。

需要明确的是,当 a = ['a', '/'];

片段 1)

return typeof a[0] === 'undefined' || a[0] === '' || a[0].match(/^[a-z0-9]+$/i) 
    && typeof a[1] === 'undefined' || a[1] === '' || a[1].match(/^[a-z0-9]+$/i) 
    && typeof a[2] === 'undefined' || a[2] === '' || a[2].match(/^[a-z0-9]+$/i);

片段 2)

if (typeof a[0] === 'undefined' || a[0] === '' || a[0].match(/^[a-z0-9]+$/i)) {
    if (typeof a[1] === 'undefined' || a[1] === '' || a[1].match(/^[a-z0-9]+$/i)) {
        if (typeof a[2] === 'undefined' || a[2] === '' || a[2].match(/^[a-z0-9]+$/i)) {
            return true;           
        }
        return false;
    }
    return false;
}
return false;

当然,如果 a[2] 由于"if"中的第一个条件而未定义,则永远不应该评估 a[2].match?

答案很简单。看看操作顺序.AND 绑定比 OR 更多。

在代码段 1 中,表达式如下所示:

a1 || b1 || (c1 && a2) || b2 || (c2 && a3) || b3 || c3

您的代码段 2 如下所示:

(a1 || b1 || c1) && (a2 || b2 || c2) && (a3 || b3 || c3)

@Christoph是对的,但你还需要添加类似的东西!== null 在匹配后

return (typeof a[0] === 'undefined' || a[0] === '' || a[0].match(/^[a-z0-9]+$/i) !==null )  && (typeof a[1] === 'undefined' || a[1] === '' || a[1].match(/^[a-z0-9]+$/i) !== null ) && (typeof a[2] === 'undefined' || a[2] === '' || a[2].match(/^[a-z0-9]+$/i) !== null);

你可以看看这个小提琴 http://jsfiddle.net/dv360q1p/1/它实现了你的问题