为什么这会在Chrome中导致无限循环?

问题描述:

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

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中有什么想法?

+0

你不能只用'localStorage.length'任何理由吗? – 2011-03-25 17:00:42

+3

当您删除“未定义”的引号时会发生什么? ''undefined'!= undefined'。 – mway 2011-03-25 17:00:51

这是因为你比较它的未定义字符串表示,而不是不确定的本身:

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

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

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

2)localStorage['asdf'] != undefined

+0

你说得对。明镜。 – doremi 2011-03-25 17:03:52

localStorage[this.config.localStoragePrefix + i] != 'undefined'总是返回true,因为您正在比较'undefined'字符串。更改为到undefined原始或使用typeof

这是因为“未定义”是不同的,那么未定义测试:P

for(var o in localStorage) if (localStorage[o]) this.config.appCount++; 
+0

解释这里发生了什么? – doremi 2011-03-25 17:03:14

+0

现在它是有道理的。 – doremi 2011-03-25 17:05:10

+0

类别。这取决于localStorage是什么类型的对象。有可能我的代码会计算函数和其他东西......您可能需要验证测试 – mplungjan 2011-03-25 17:11:05