多个OR字符串

时间:2014-03-26 09:12:34

标签: javascript string if-statement return-value

我无法找到如何在If语句中传递多个字符串。

这是我的代码:

    var date = new Date();

    if (document.getElementById("postcode-entry").value == ("G74" || "G75")) {
        if (date.getHours() < 8 ) {
            window.alert("Sorry we are not open at the moment, please try again later.");
        } else {
            window.open("http://http://stackoverflow.com");
        }
    } else {
        window.alert("Sorry we do not Delivery to your area, please collect from store");
    }

我该怎么做?

4 个答案:

答案 0 :(得分:3)

短语("G74" || "G75")强制对每个字符串进行布尔评估,并且两者都将始终返回true。

所以你需要做这样的事情:

var myvar = document.getElementById("postcode-entry").value;

if(myvar === "G74" || myvar === "G75")

答案 1 :(得分:2)

我不确定您是否要遵循此方法,但请尝试使用以下内容 -

var strArr = [ 'G74', 'G75' ];

if( strArr.indexOf( document.getElementById("postcode-entry").value ) !== -1 ) {
// Your  normal code goes  here
}

使用它,你可以在if。

中的单个语句中测试n个字符串

答案 2 :(得分:0)

这应该

 var post_code = document.getElementById("postcode-entry").value;
  if (post_code == "G74" || post_code == "G75") 

答案 3 :(得分:0)

我以前从未见过这个。也许你可以使用switch语句

但在你的情况下,我会建议以下内容:

var poscode = document.getElementById("postcode-entry").value
if (postcode === "G74" || postcode === "G75") ......