简体   繁体   English

无法获取if语句以比较javascript中的两个字符串

[英]Can't get if statement to compare two strings in javascript

In my code when i equals 5 myDate should be equal to it. 在我的代码中,当i等于5时, myDate应该等于它。 The alert shows me that they are the same. 警报告诉我它们是相同的。 I can never get the function to return 1; 我永远无法获得return 1;的函数return 1;

function checkForHoliday(date) {
    var myDate = new Date(date);
    myDate = myDate.getMonth() + "/" + myDate.getDate() + "/" + myDate.getFullYear();

    alert(myDate + "\n" + holidays[5]);

    for (i = 0; i <= 9; i++) {
       if (myDate == holidays[i]) {
           return 1;
           alert("got it");
       }       
    }

    return 0;
}

This is what the string in the array looks like: 这是数组中的字符串如下所示:

year = 2013
holidays[5] = "7/2/" + year

My alert shows me this: 我的警报向我显示了这一点: 在此处输入图片说明

I have run your code locally, and have it working. 我已经在本地运行您的代码,并且可以正常工作。

I'm going to guess that your issue stems from the fact that Date.getMonth() returns month numbers where January === 0. That throws a lot of people off. 我猜您的问题源于Date.getMonth()返回1月=== 0的月份数字的事实。这使很多人失望。

To recreate your code, I simply used Chrome's console. 要重新创建代码,我只使用了Chrome的控制台。 I also changed your alert to a console.log to save myself the hassle of using alert . 我还将您的警报更改为console.log ,以免自己使用alert的麻烦。

Here's the code: 这是代码:

function checkForHoliday(date) {
  var myDate = new Date(date);
  myDate = myDate.getMonth() + "/" + myDate.getDate() + "/" + myDate.getFullYear();

  console.log(myDate + "\n" + holidays[5]);

  for (i = 0; i <= 9; i++) {
    if (myDate == holidays[i]) {
      return 1;
    }
  }

  return 0;
}

And a fake holiday array: 还有一个假的假期数组:

holidays = [0,1,2,3,4,'7/2/2013']

(The 7 here actually corresponds to August) (此处的7实际上对应于8月)

Upon running checkForHoliday('8/2/2013') , the console reports back a response of 1 . 运行checkForHoliday('8/2/2013') ,控制台将报告响应1 The code successfully matches the date. 该代码成功匹配日期。

If you actually intended for holiday[5] to represent July 2nd, 2013, you'll need to set holiday[5] = '6/2/2013' . 如果您实际上打算将holiday[5]表示为2013年7月2日,则需要设置holiday[5] = '6/2/2013' 6/2/2013 holiday[5] = '6/2/2013'

Try Using this, 试试这个

 <script type="text/javascript">

    var startYear = parseInt(document.getElementById('startYear'), 10);
    var startMonth = parseInt(document.getElementById('startMonth'), 10) - 1; 
    var startDay = parseInt(document.getElementById('startDay'), 10);
    var myDate = new Date(startYear, startMonth, startDay);

</script>

Convert the date object to string in desired format. 将日期对象转换为所需格式的字符串。 Use triple equals operator to test equality. 使用三重等于运算符测试相等性。

Try: 尝试:

if (myDate.toLocaleDateString() === holidays[i]) {
    return 1;
    alert("got it");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM