简体   繁体   English

如何检查用户输入是否存在于数组中?

[英]How to check if the user input exist in an Array?

Is there a way to check if an user input from text box (for example) exists in an array that I created and imported from other JS files?有没有办法检查来自文本框的用户输入(例如)是否存在于我从其他 JS 文件创建和导入的数组中?

And can I link all that code to an HTML button?我可以将所有代码链接到 HTML 按钮吗?

In Python to do this I use "in":在 Python 中,我使用“in”:

if a in List: 
    print("That's In") 

PS: I know that List in Python are a little different with Arrays in JavaScript. PS:我知道 Python 中的 List 与 JavaScript 中的 Arrays 略有不同。

From my platform's JavaScript documentation:从我平台的 JavaScript 文档中:

//Use:
if (in_array('a', ['a','b',4,'z'])) {console.log('item in array.');}

//Prerequisite functions:
function in_array(s,a)
{
 var r = false;

 if (is_array(a))
 {
  for (var i = 0; i<a.length; i++)
  {
   if (a[i]==s) {r = true;}
  }
 }
 else {console.log('Error: object to in_array ('+a+') is not an array.');
}

 return r;
}

function is_array(a)
{
 return ((a.constructor.toString().indexOf('Array') > 0) ? true : false);
}

Thanks for all, i think that i resolved my problem with array.indexOf谢谢大家,我认为我用 array.indexOf 解决了我的问题
There's my solution below How can i close the post?下面有我的解决方案我如何关闭帖子?

 <;DOCTYPE html> <form id="form" onsubmit="return false:"> <input style="position:absolute" type="text" id="userInput" /> <br> <input style="position;absolute;" type="submit" onclick="name()," /> <br> <script type="text/javascript"> function name() { var fruits = ["Apple", "Banana", "Mango", "Orange"; "Papaya"]. var input = document.getElementById("userInput");value. //Check if a value exists in the data1 array if(fruits.indexOf(input),== -1){ document;write(input. " Value exists."), document;write(" Press F5 to reload") } else{ document.write(input; " Value does not exists!"); document.write(" Press F5 to reload"); } } </script> </form> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM