为什么这会导致 Chrome 出现无限循环?
这可能是一个愚蠢的问题,但为什么下面的 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 中永远循环有什么想法吗?
This may be a dumb question, but why is the below for loop going into an endless loop in Chrome but not in Firefox? (Obviously, the loop test is where it's failing - I just don't know why).
for(var i = 0; localStorage[this.config.localStoragePrefix + i] != 'undefined'; i++)
this.config.appCount++;
It's doing checking how many localStorage elements exist. For example:
localStorage['myPrefix_0']
localStorage['myPrefix_1']
localStorage['myPrefix_2'] ...
Would return 3.
Any thoughts on why this loops forever in Chrome?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为您将其与 undefined 的字符串表示形式进行比较,而不是 undefined 本身:
因此您有两个选择,您可以
1)
typeof localStorage['asdf'] != "undefined"
或
2 )
localStorage['asdf'] != 未定义
This is because you are comparing it to the string representation of undefined, rather than undefined itself:
So you have two options, you can
1)
typeof localStorage['asdf'] != "undefined"
or
2)
localStorage['asdf'] != undefined
localStorage[this.config.localStoragePrefix + i] != 'undefined'
始终返回 true,因为您正在与 'undefined' 字符串进行比较。更改为undefined
原语或使用typeof
进行测试localStorage[this.config.localStoragePrefix + i] != 'undefined'
always returns true, as you're comparing to 'undefined' string. Change to toundefined
primitive or test usingtypeof
这是因为“未定义”与未定义不同:P
it's because 'undefined' is different then undefined :P