将提示输入与数组值匹配

时间:2016-02-21 20:51:58

标签: javascript arrays

我正在玩一些基本的js,我刚开始学习,到目前为止,我有以下代码。我试图询问用户他们的名字是什么,然后告诉他们他们是否与赛车手同名(来自我的阵列 driversNames )。

如果他们与赛车手的名字相同,那么就会告诉他们这样做,如果不是,就会告诉他们不会。但是我觉得我在这里有问题: if(yourName === driversNames)但我无法理解。

我输入提示符并不重要,它总是说抱歉你没有相同的名字。

var driversNames = ["Lewis", "Fernando", "Sebastian", "Jenson", "Daniel"]
for (var i = 0; i < driversNames.length; i++) {
  console.log(driversNames[i] + " " + "is a drivers name");
}

var yourName = prompt("What is your name?")

console.log("Your name is" + " " + yourName)

if (yourName === driversNames) {
  console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!")
} else {
  console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers")
}

2 个答案:

答案 0 :(得分:4)

您正在将字符串与数组进行比较,因此比较将返回false。你有几个选项来解决这个问题 - 我将解释使用循环来检查每个字符串,并使用indexOf

循环:您需要遍历driversNames数组中的每个元素并比较每个元素。这是手动方式。

var sameName = false; //flag to keep track of if name matches or not
driversNames.forEach(function(name) { //loop through each name in driversNames
    if(yourName === name) { //compare your name to driver name
        sameName = true; //if match, set flag to true
    }
}); //loop ends here
if(sameName) { //if flag is true, a name matched
        console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //Console log success statement
} else { // else, no name matched
      console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}

IndexOf:此方法使用较少的代码行,但在所有浏览器上都不兼容 - 我相信IE8下的任何内容在使用时都会中断。但如果兼容性不是问题,它看起来像这样:

if (driversNames.indexOf(yourName) > -1) { //indexof returns -1 for no match, and a number for match
  console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //console log success statement
} else {
  console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}

indexof稍微优雅一点,虽然容易忘记兼容性问题。代码被注释但只是为了解释它:数组有一个你可以调用的方法,称为indexOf(),它接受​​一个参数。然后,此方法将检查该参数是否在数组中,如果是,则返回一个值,该值是数组中的位置。如果它不在数组中,它将返回-1

答案 1 :(得分:4)

你在这一行if (yourName === driversNames)中犯了一个错误。 它不会将您的名字与driversNames中的名称进行比较。最简单的方法:使用indexOf方法。所以这一行应该如下所示

if (driversNames.indexOf(yourName) > -1) //Get Name otherwise no 

jsfiddle示例适用于您,indefOf链接

由于