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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:33:35  来源:igfitidea点击:

IE 11 Unable to get property 'length' of undefined or null reference

javascriptjqueryinternet-explorer-11

提问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.localStorageis undefined initially. You are checking is localStoragein the windowand its not null. So bSupportLocalis setting to true. Its executing window.localStorage.lengthstatement. Undefined.length causing error. Here is the code

我认为在 IEwindow.localStorage中最初是未定义的。您正在检查是localStoragewindow和不是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,否则分配给空字符串。