【问题标题】:Why does this cause an endless loop in Chrome?为什么这会导致 Chrome 中的无限循环?
【发布时间】:2011-03-25 16:59:32
【问题描述】:

这可能是一个愚蠢的问题,但为什么下面的 for 循环在 Chrome 中进入无限循环,而在 Firefox 中却没有? (显然,循环测试是它失败的地方——我只是不知道为什么)。

for(var i = 0; localStorage[this.config.localStoragePrefix + i] != 'undefined'; i++)
   this.config.appCount++;

它正在检查存在多少 localStorage 元素。例如:

localStorage['myPrefix_0']
localStorage['myPrefix_1']
localStorage['myPrefix_2'] ...

将返回 3。

关于为什么这会在 Chrome 中永远循环的任何想法?

【问题讨论】:

  • 有什么理由不能只使用localStorage.length
  • 删除 'undefined' 周围的引号后会发生什么? 'undefined' != undefined.

标签: javascript html for-loop local-storage


【解决方案1】:

这是因为您将它与 undefined 的字符串表示形式进行比较,而不是 undefined 本身:

localStorage['asdf']
>>undefined
localStorage['asdf'] == undefined
>>true
localStorage['asdf'] == 'undefined'
>>false

所以你有两个选择,你可以

1)typeof localStorage['asdf'] != "undefined"

2)localStorage['asdf'] != undefined

【讨论】:

    【解决方案2】:

    localStorage[this.config.localStoragePrefix + i] != 'undefined' 始终返回 true,因为您正在与“未定义”字符串进行比较。更改为undefined 原语或使用typeof 进行测试

    【讨论】:

      【解决方案3】:

      这是因为“未定义”与未定义不同:P

      【讨论】:

        【解决方案4】:
        for(var o in localStorage) if (localStorage[o]) this.config.appCount++;
        

        【讨论】:

        • 解释这里发生了什么?
        • 有点。这取决于 localStorage 是什么类型的对象。我的代码可能会计算函数和其他内容...您可能需要对测试进行限定
        猜你喜欢
        • 2013-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-06
        • 1970-01-01
        • 2012-09-27
        • 2011-07-31
        相关资源
        最近更新 更多