IE 11无法获取未定义或空引用的属性“长度”

我在Internet Explorer 11中收到错误

“无法在线获取未定义或空引用的属性’长度’

if (window.localStorage.length !== 0) 

它在chrome和Firefox上运行良好,不确定是什么导致它

  function initialize() { // test to see if brouser supports storeage api var bSupportsLocal = (('localStorage' in window) && window.localStorage !== null ); if (!bSupportsLocal) { document.getElementById('infoform').innerHTML = "

Sorry, This browser does not suport local storage.

"; 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;

我认为在IE window.localStorage中.localStorage最初是未定义的。 您正在检查window localStorage ,它不是null 。 所以bSupportLocal设置为true。 它执行window.localStorage.length语句。 Undefined.length导致错误。 这是代码

  var bSupportsLocal = window['localStorage'] || ''; 

如果localStorage具有某个值,它将分配给bSupportsLocal,否则将为其分配空字符串。