当vm8出现一个不存在的属性时,它显示一个包含以下消息的错误:
无法读取null属性'value'例如pass id不存在:
var pass = document.getElementById('pass');
if (pass.value == '') //here is error that complain about null property
我的问题是我们如何防止编译器满足这行代码与适当的条件?由于
// Get the element.
// If the element doesn't exist, then it will be `null`
var pass = document.getElementById('pass');
if (pass) {
alert(pass.value);
} else {
alert("Element was not found. There is a problem.');
}
行:if (pass)
也可以写成if (pass !== null)
,但是没有必要这样写。
代替if (pass.value == '')
,试试
if (typeof(pass.value) == 'undefined')
您可以通过多种方式:
if(typeof(pass.value) === 'undefined')
if(typeof(pass)==="undefined")
if('value' in pass)