Saturday 15 September 2012

How can I use a Function to determine if a Value exists in a Javascript Array? -


I am using an input field where a person types in a value.
I will create variables, which they will type in: 'Ben'
I want to loop to work through the name and return right or wrong.

The script is not working and I know it's not that simple.

  function valid name () {var name = "Ben"; Var NameArere = ["Bill", "Barry", "Jack", "Will"]; Var array length = nameArray.line; (Var i = 0; i & lt; SimpleLeal; i ++) {// Do something if (name! = Name Array [i]) {Warning ((name [i]) + "Name is not valid.") ; Console.log ("The name is not found in the array."); } And {return true; Console.log (nameArray [i]); }}}}  

The only way for your loop logic to know that the value Not in the array is to go before the entire array. Your loop will be cautious every move until it gets a match. Even putting return after return does not mean it will not be executed before:

.indexOf () , and it returns -1 when no one matches:

  function validateNames ( ) {Var name = "Ben"; Var NameArere = ["Bill", "Barry", "Jack", "Will"]; Return name here Indexof (name)! == -1; }  

No comments:

Post a Comment