如何检查 if 条件用户输入的单词是否存在于分配给变量的数组中

请参阅评论后的第2行。这个问题在代码注释中有提到。


//valid input to be taken by user

var validanswerone = ["yes" , "YES", "Yes"];//here i want to take multiple form of input the user might type but my efforts are going effort less.

var validanswertwo = "no";//only this is working.


//conditions

if (userage === validanswerone){

  console.log("\n\nPlease put your credit card details in the next page" + ", you will be redirected soon!");

}

else if(userage === validanswertwo){

  console.log("\n\nWe are sorry!");

  console.log("\n\nPlease try back in" + "  *days remaining to be become 18+ will be added in the coming update still not understood the formula to implicate it*");

}

else{

  console.log("\n\nInvalid input!")

}


梦里花落0921
浏览 119回答 4
4回答

慕田峪4524236

validanswerone是一个数组,您应该使用以下命令检查它Array#includes:if (validanswerone.includes(userage)) {    ... }

素胚勾勒不出你

这是问题的解决方案。通过使用将所有输入转换为大写或小写var age = userage.toUpperCase();我能够以任何格式输入输入,该输入会自动转换为我的条件,在本例中为大写。请有人帮助我正确地重新表述问题并发布答案,以便需要此答案的人能够轻松找到它。var readlineSync = require('readline-sync');//question asked to the uservar userage = readlineSync.question("Are you above the age of 18 for the purchase of the tickets \n(*as of DEC-2020) " + " : ");var age = userage.toUpperCase();//valid input to be taken by uservar validanswerone = "YES";var validanswertwo = "NO";//conditionsif (age === validanswerone){  console.log("\n\nPlease put your credit card details in the next page" + ", you will be redirected soon!");}else if(age === validanswertwo){  console.log("\n\nWe are sorry!");  console.log("\n\nPlease try back in" + "  *days remaining to be become 18+ will be added in the coming update still not understood the formula to implicate it*");}else{  console.log("\n\nInvalid input!")}//final-outputconsole.log("\n\nThank you, you will be redirected soon!")希望有一天这能解决某人的一些问题!

ibeautiful

如果数组仅包含字符串值,并且数组包含类似 [ {id:1,name:"Aditya"} ] 的对象,则可以使用Array.includes() 。那么您应该使用Array.some()因为它在迭代数组中的事件元素时应用比较逻辑。

慕妹3242003

您可以使用 JavaScript 中的 include 函数,无论数组中是否存在用户,它都可以为您提供输出!像这样“validanswerone.includes(userage)”,更好的方法是如果您仅为多种形式的 YES 或 NO 创建一个数组(您可以使用 .tolower 或 .toCapital 函数检查它)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript