当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why does this cause an endless loop in 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?

网友答案:

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

网友答案:

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

网友答案:

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

网友答案:
for(var o in localStorage) if (localStorage[o]) this.config.appCount++;
分享给朋友:
您可能感兴趣的文章:
随机阅读: