开发者

Checking undefined value not working?

开发者 https://www.devze.com 2023-03-12 06:23 出处:网络
I have the following javascript code: var currentIds = localStorage.getItem(\'currentPairsIds\'); if ((typeof currentIds === \"undefined\") ||

I have the following javascript code:

var currentIds = localStorage.getItem('currentPairsIds');

if ((typeof currentIds === "undefined") ||
    (currentIds == null))
        $.myNameSpace.currentIDs = new Array(3);
    else
        $.myNameSpace.currentIDs = currentIds.Split(',');

I'm debugging with Firebug and al开发者_如何学运维though currentIds hasn't got any value it always executes else statement.

UPDATE:

I'm getting this value from HTML5 storage.

What am I doing wrong?


This is how I have solved my problem:

var currentIds = localStorage.getItem('currentPairsIds');

if ((currentIds === undefined) ||
    (currentIds == null) || (currentIds == "undefined"))
        $.myNameSpace.currentIDs = new Array(3);
    else
        $.myNameSpace.currentIDs = currentIds.split(',');

localStorage.getItem('currentPairsIds'); returns the string "undefined".

There is another error in Split() function. The right version is without any capital letter.


I would use a direct comparison instead of the notoriously odd "typeof" operator:

if ((currentIds === undefined) || (currentIds === null)) {
  //...


It's not working because localStorage.getItem returns null if the item is not defined, it does not return undefined http://dev.w3.org/html5/webstorage/#dom-storage-getitem

Example: http://jsfiddle.net/mendesjuan/Rsu8N/1/

var notStored = localStorage.getItem('ffff');

alert(notStored); // null
alert(typeof notStored); // object, yes, null is an object.

Therefore you should just be testing

alert(notStored === null);


I think you have to make checking for undefined comparing with == instead of ===. Example:

typeof currentIds == "undefined"

This will make sure, the variable is really undefined or not.



[Edit Edit Edit Edit :P]


currentIds = "undefined"

implies

typeof currentIds == "String"

Also see, Detecting Undefined, === isn't necessary for string comparison.


In my case LocalStorage.getItem() was converting it to "undefined" as string. I also needed to check if it s "undefined" as a string.

var myItem = LocalStorage.getItem('myItem');
if(myItem != "undefined" && myItem != undefined && myItem != null){
    ...
}


if( typeof(varName) != "undefined" && varName !== null )

be sure, you use ( " " ) quotes when checking with typeof()

0

精彩评论

暂无评论...
验证码 换一张
取 消