为什么这会导致 Chrome 出现无限循环?

发布于 2024-10-27 14:00:12 字数 435 浏览 7 评论 0原文

这可能是一个愚蠢的问题,但为什么下面的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

旧城烟雨 2024-11-03 14:00:12

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

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

因此您有两个选择,您可以

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:

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

So you have two options, you can

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

or

2) localStorage['asdf'] != undefined

素衣风尘叹 2024-11-03 14:00:12

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 to undefined primitive or test using typeof

红ご颜醉 2024-11-03 14:00:12

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

it's because 'undefined' is different then undefined :P

楠木可依 2024-11-03 14:00:12
for(var o in localStorage) if (localStorage[o]) this.config.appCount++;
for(var o in localStorage) if (localStorage[o]) this.config.appCount++;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文