我正在玩一些我刚开始学习的基本 js,到目前为止我有下面的代码。我试图询问用户他们的名字是什么,然后告诉他们他们是否与赛车手共享相同的名字(来 self 的数组 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")
}
最佳答案
你在这一行 if (yourName === driversNames)
中犯了一个错误。
它不会将您的姓名与 driversNames
中的姓名进行比较。最简单的方法:使用 indexOf
方法。所以这一行应该像下面这样
if (driversNames.indexOf(yourName) > -1) //Get Name otherwise no
谢谢
关于javascript - 将提示输入与数组值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541874/