javascript IE 11 无法获取未定义或空引用的属性“长度”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31908951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IE 11 Unable to get property 'length' of undefined or null reference
提问by brodster
I am getting an error in internet explorer 11
我在 Internet Explorer 11 中遇到错误
"Unable to get property 'length' of undefined or null reference" on line
在线“无法获取未定义或空引用的属性‘长度’”
if (window.localStorage.length !== 0)
it works fine on chrome and Firefox, not sure whats causing it
它在 chrome 和 Firefox 上运行良好,不确定是什么原因造成的
<script>
function initialize() {
// test to see if brouser supports storeage api
var bSupportsLocal = (('localStorage' in window) && window.localStorage !== null );
if (!bSupportsLocal) {
document.getElementById('infoform').innerHTML = "<p> Sorry, This browser does not suport local storage. </p>";
return;
}
if (window.localStorage.length !== 0) {
document.getElementById('firstName').value = window.localStorage.getItem('firstName');
$.mobile.navigate("#benefits-facts");
}
}
function storeLocalContent(fName) {
window.localStorage.setItem('firstName', fName);
}
function clearLocalContent(strToStore) {
window.localStorage.clear();
}
window.onload = initialize;
</script>
回答by Anil Talla
I thought in IE window.localStorage
is undefined initially. You are checking is localStorage
in the window
and its not null
. So bSupportLocal
is setting to true. Its executing window.localStorage.length
statement. Undefined.length causing error.
Here is the code
我认为在 IEwindow.localStorage
中最初是未定义的。您正在检查是localStorage
在window
和不是null
。因此,bSupportLocal
被设置为true。它的执行window.localStorage.length
语句。Undefined.length 导致错误。这是代码
var bSupportsLocal = window['localStorage'] || '';
If localStorage is having some value it will assign to bSupportsLocal, otherwise it is assigned with empty string.
如果 localStorage 有某个值,它将分配给 bSupportsLocal,否则分配给空字符串。