JavaScript短路评估错误
JavaScript short circuit evaluation error?
下面的两个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/它实现了你的问题
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- 类型错误'未定义'不是对象(正在评估'navigator.connection.type'
- 删除评估值Javascript时的错误
- JavaScript短路评估错误
- 类型错误:'null'不是对象(正在评估'响应.productType')
- 在undercore.js微模板中评估数据的错误做法
- "类型错误:'null'不是对象(正在评估“a.nodeType')”;在phanto
- 类型错误:'未定义'不是Sencha Touch和cordova 3.0的功能(评估'cordo
- 错误:undefined不是对象(正在评估'$scope.inputcode.password')
- 评估 json 错误
- 为什么我收到错误“document.write 可以是一种评估形式”
- Javascript 错误:TypeError:“null”不是 safari 上的对象(评估“event.target
- 类型错误:'未定义'不是对象(正在评估'requireDirs.forEach')
- 类型错误:'未定义'不是函数(正在评估'audio_volume.toPreccision(2)
- JavaScript中途停止执行并评估错误答案?,Console.log是正确的
- Highcharts错误:TypeError:undefined不是对象(正在评估'chart.yAxis
- 从命令行评估JavaScript文件的运行时/加载错误
- 类型错误:'未定义'不是对象(正在评估'promise.data.map')
- React Native + Firebase 登录错误:Undefind 不是对象(评估 'this.props.na