开发者社区> 问答> 正文

if(window.localStorage.checkOutDate==null)这条语句不能执行的原因?

我的js代码如下,if后面的语句永远等不到执行,请问怎么破?

<script type="text/javascript"> $(document).ready(function(){ window.localStorage.checkInDate=null; window.localStorage.checkOutDate=null; $("#test1").html(window.localStorage.checkInDate); $("#test2").html(window.localStorage.checkOutDate); $("span").bind("click",function(){ $("#test1").html("hello"); if (window.localStorage.checkInDate==null) { window.localStorage.checkInDate = $(this).attr("title"); $("#test1").html(window.localStorage.checkInDate); } else { window.localStorage.checkOutDate = $(this).attr("title"); $("#test2").html(window.localStorage.checkOutDate); } }); }); </script> 

展开
收起
杨冬芳 2016-06-16 18:04:32 2291 0
1 条回答
写回答
取消 提交回答
  • IT从业

    checkInDate 和checkOutDate 都是localStorage对象上用户自定义的属性。这些属性虽然可以被赋值为一个对象,但是实际存储都是字符串,会调用对象的适当方法(toString或者valueOf)进行转换。

     var a = {};  
     window.localStorage.checkInDate = a;   
     window.localStorage.checkOutDate = null;                   
     console.log(window.localStorage.checkInDate);  // "[Ojbect Ojbect]"
     console.log(window.localStorage.checkOutDate); // "null"   
     console.log(typeof (window.localStorage.checkInDate));  // string
     console.log(typeof (window.localStorage.checkOutDate)); // string
    
    

    所以这句 if(window.localStorage.checkOutDate==null) 等价于 if ("null" == null) . 是不可能成立的。
    另外建议楼主以后贴代码的时候,最好格式化。

    2019-07-17 19:41:42
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载