how to compare two strings in javascript if condition

我与影子孤独终老i 提交于 2019-11-30 16:08:08

问题


I'm having trouble recalling how to compare these two strings in an if statement. What I'm string to do is check if my variable compare equals page1 or page2 if not, go to the else statement.

var compare = "page3";

if (compare === "page1" || "page2") {
  document.body.innerHTML = "github url";
} else {
  document.body.innerHTML = "non-github url";
}

回答1:


You could check every option.

if (compare === "page1" || compare === "page2") {

Or you could use an array and check with an existential quantifier like Array#some against, like

if (["page1", "page2"].some(a => a === compare)) {

var compare = "page3";

if (compare === "page1" || compare === "page2") {
    document.body.innerHTML = "github url";
} else {
    document.body.innerHTML = "non-github url";
}



回答2:


Anytime you have multiple things to check in an if condition, you must write each condition separate from the other. So, the test must be written as:

// If compare equals "page1" OR compare equals "page2"
if (compare === "page1" || compare === "page2") {

When you have a single variable that may contain many different values, using a switch statement can be more logical and more efficient since it only has to look up the value of the variable one time.

Also, remember that strings are literals and "page1" does not equal "Page1". To make a comparison that is case-insensitive, you can force all the values to lower (or upper) case first and then check them against each other (as shown here):

switch (compare.toLowerCase()) {
    case "page1" :
        // Do work here
        break;
    case "page2" :
        // Do work here
        break;
    case "page3" :
        // Do work here
        break;
    default :
        // Do work here
        break;
}


来源:https://stackoverflow.com/questions/42319247/how-to-compare-two-strings-in-javascript-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!