为什么这会在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中有什么想法?
答
这是因为你比较它的未定义字符串表示,而不是不确定的本身:
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
你不能只用'localStorage.length'任何理由吗? – 2011-03-25 17:00:42
当您删除“未定义”的引号时会发生什么? ''undefined'!= undefined'。 – mway 2011-03-25 17:00:51