检查未定义的值不起作用?
我有以下 javascript 代码:
var currentIds = localStorage.getItem('currentPairsIds');
if ((typeof currentIds === "undefined") ||
(currentIds == null))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.Split(',');
我正在使用 Firebug 进行调试,尽管 currentIds
没有任何值,但它始终执行 else
语句。
更新:
我从 HTML5 存储中获取此值。
我做错了什么?
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 although 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这就是我解决问题的方法:
localStorage.getItem('currentPairsIds');
返回字符串“undefined”
。Split()
函数中存在另一个错误。正确的版本是没有任何大写字母。This is how I have solved my problem:
localStorage.getItem('currentPairsIds');
returns the string"undefined"
.There is another error in
Split()
function. The right version is without any capital letter.我会使用直接比较,而不是臭名昭著的奇怪的“typeof”运算符:
I would use a direct comparison instead of the notoriously odd "typeof" operator:
它不起作用,因为
localStorage.getItem
返回null
如果该项目未定义,则不会返回undefined
http://dev.w3.org/html5/webstorage/#dom-storage-getitem示例: http://jsfiddle.net/mendesjuan/Rsu8N/1/
因此你应该正在测试
It's not working because
localStorage.getItem
returnsnull
if the item is not defined, it does not returnundefined
http://dev.w3.org/html5/webstorage/#dom-storage-getitemExample: http://jsfiddle.net/mendesjuan/Rsu8N/1/
Therefore you should just be testing
我认为你必须检查
undefined
与==
而不是===
进行比较。示例:
这将确保变量是否确实未定义。
I think you have to make checking for
undefined
comparing with==
instead of===
.Example:
This will make sure, the variable is really undefined or not.
[编辑编辑编辑编辑:P]
意味着
另请参阅,检测未定义,字符串比较不需要===。
[Edit Edit Edit Edit :P]
implies
Also see, Detecting Undefined, === isn't necessary for string comparison.
就我而言,LocalStorage.getItem() 将其转换为“未定义”字符串。
我还需要检查它是否作为字符串“未定义”。
In my case LocalStorage.getItem() was converting it to "undefined" as string.
I also needed to check if it s "undefined" as a string.
确保在使用
typeof()
检查时使用 (" ") 引号be sure, you use ( " " ) quotes when checking with
typeof()