JQ时间比较,为什么不相等?

    var time = new Date();
    var nowDay = time.toLocaleDateString().replace(/\//g, '-');
    var createtime_Y = unix_to_datetime(1459407384, 1);
    function unix_to_datetime(unix, type) {
        var now = new Date(parseInt(unix) * 1000);
        var Y = now.getFullYear() + '-';
        //0-11,0代表1月
        var M = now.getMonth()+1 + '-';
        var D = now.getDate() + ' ';
        var h = (now.getHours() < 10 ? '0'+(now.getHours()) : now.getHours()) + ':';
        var m = (now.getMinutes() < 10 ? '0'+(now.getMinutes()) : now.getMinutes()) + ':';
        var s = (now.getMinutes() < 10 ? '0'+(now.getMinutes()) : now.getMinutes());
        switch(type) {
            case 1:
                return Y+M+D;
            case 2:
                return h+m+s;
            case 3:
                var M = (now.getMonth()+1 < 10 ? '0'+(now.getMonth()+1) : now.getMonth()+1) + '月';
                return M+D+h+m+s;
        }
    }
        console.log(nowDay);
        console.log(typeof(nowDay));
        console.log(createtime_Y);
        console.log(typeof(createtime_Y));
        if (nowDay == createtime_Y) {
            console.log(1);
        } else {
            console.log(2);
        }

图片描述

如图?why?
为什么输出的是2???求解

阅读 2.6k
2 个回答
var D = now.getDate() + ' ';

nowDay 31后面有空格。去掉空格试试吧,不对的话我就不知道了。另外==等号不是严格相等,不用查看类型,类型不一样也相等。

var D = now.getDate()+''; 这里,你的后边是一个空格吧,那么下边的if语句,两个字符串比较,createtime_Y末尾多了一个空格,当然不等了。你去掉那个空格试下看看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题