比较用户的字符串

时间:2019-05-21 15:56:48

标签: javascript

如果用户输入了特定的符号或字符串,我想启动代码。 在此任务中,我需要检查用户是否输入了以下任何内容:“ a”,“ b”,“ c”,“ d”。但是,它似乎只是忽略了if语句。

这是整个问题: 编写一个程序,根据其标签和等级确定棋盘方块的颜色。 输入:在第一行,您将收到L-标签 在第二行,您将收到R-排名

let L = prompt();
let R = Number(prompt());
if (L == ("a", "c", "e", "g")) {
  if (R % 2 == 0) {
    /*if we are on a/c/e/g lines and the number is even the 
                         square is white*/
    console.log("light");
  } else {
    console.log("dark");
  } //else it is going to be odd therefore dark
} else if (L == ("b", "d", "f", "h")) { //opposite logic:
  if (R % 2 == 0) {
    console.log("dark");
  } else {
    console.log("light");
  }
}

问题是我不知道如何比较两个字符串。我尝试了一些字符串方法,但我想我只是在犯一个sintax错误

2 个答案:

答案 0 :(得分:0)

==的比较不能那样工作。将代码分成多个or (||) statements或使用数组:

或者:

var L = "e";
if (L == "a" || L == "c" || L == "e" || L == "g"){
    console.log("Or method");
}

数组-包括:

var L = "c";
if (["a", "c", "e", "g"].includes(L)){
    console.log("includes method")
}

数组-indexOf:

var L = "g";
if (["a", "c", "e", "g"].indexOf(L) !== -1){
    console.log("indexOf method");
} 


有关JavaScript中逻辑运算符的更多信息:

https://javascript.info/logical-operators

答案 1 :(得分:-1)

("a","c","e","g")是一个使用逗号运算符的表达式,它将计算为其最后一个操作数(在上述情况下为"g")。所以

if(L==("a","c","e","g")){..}

相同
if(L == "g"){...}

您可以创建数组,然后使用includes()

let L = prompt();
let R = Number(prompt());
if (["a", "c", "e", "g"].includes(L)) {
    if (R % 2 == 0) {
        console.log("light");
    } else {
        console.log("dark");
    } 
} else
if (["b", "d", "f", "h"].includes(L)) { 
    if (R % 2 == 0) {
        console.log("dark");
    } else {
        console.log("light");
    }
}

您可以使代码更短。创建一个同时包含字母数组的数组,并将其中存在indexOf的{​​{1}}数组添加到L

R