javascript 在返回 true 之前检查输入值是否与数组中的任何值匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16821578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking to see if the input value matches any value within an array before returning true
提问by user2433761
I'm trying to validate a form using javascript. Checking to see if the input value matches any value within an array before returning true.
我正在尝试使用 javascript 验证表单。在返回 true 之前检查输入值是否与数组中的任何值匹配。
Here's an example of what I have written so far. Yet this seems to not work.
这是我到目前为止所写的一个例子。然而这似乎行不通。
<script type='text/javascript'>
function checkForm()
{
var agent = document.getElementById('agent').value;
var myArray = new Array()
myArray[0] = 'First Agent';
myArray[1] = 'Second Agent';
myArray[2] = 'Third Agent';
if (agent != myArray)
{
alert("Invalid Agent");
return false;
}
else
{
return true;
}
}
<form>
<fieldset>
Agents Name*
<input type="text" size="20" name="agent" id="agent">
</fieldset>
</form>
回答by Wellington Zanelli
You need to make a for structure to pass your entire array, when value matches you return true, otherwise return false. Something like this:
您需要创建一个 for 结构来传递整个数组,当值匹配时返回 true,否则返回 false。像这样的东西:
for (var i = 0; i < myArray.length; i++) {
if (agent == myArray[i])
return true;
}
return false;
回答by Niccolò Campolungo
function checkForm() {
var agent = document.getElementById('agent').value;
var myArray = ['First Agent', 'Second Agent', 'Third Agent'];
if(myArray.indexOf(agent) == -1) //returns the index of the selected element
{
alert("Invalid Agent");
return false; // if you return false then you don't have to write the else statement
}
return true;
}
回答by lasote
"agent != myArray" compares your string with an array, not with its contents. Look at this post: Determine whether an array contains a value
“agent != myArray”将您的字符串与数组进行比较,而不是与其内容进行比较。看这个帖子: 确定一个数组是否包含一个值
回答by Jafin
With Underscore/lodash you could do:
使用 Underscore/lodash 你可以这样做:
if (_.indexOf(myArray,agent) == -1)
{
//alert invalid agent
...
}