I have a simple query and I'm not sure why the array content is not returning properly. I'm pretty sure this is something easy, but in some way I can not find the result. The scenario is that a variable "comparison" is set to a value eg. "Apple" and I am looping in the array, and, if the SafeMe matches the text field with an index print. It does not do this and it always says "not equal" value, it works for the dog, it looks like it reaches the final array, then compares. help please.
The code below
function print (msg) {document.getElementById ("demo") .innerHTML + = msg + '& lt; / Br & gt; '; } Function myFunction () {var text = ""; Var i; Var arr = ["apple", "banana", "carrot", "dog"]; Var comparison = document.getElementById ('compare'). value; If (compare!) {Print ('comparison is empty'); Return; } Other {print (compare with 'comparison'); } (I = 0; i & lt; arr.length; i ++) {if compare (ARE [I] ==) {Print ("value is on index" + + "is" + AR [I]); Return; // found out, break out for loop) and if (arr [i]! = Compare) {print ("not the same"); } Other {print ("some error"); }} Print ("" + Comparison + "in Array"); }
& lt ;! DOCTYPE html & gt; & Lt; Html & gt; & Lt; Body & gt; & Lt; Script & gt; & Lt; / Script & gt; & Lt; P & gt; Click on the button to loop one with a break. & Lt; / P & gt; & Lt; Input type = "text" id = "compare" placeholder = "compare" /> & Lt; Button onclick = "myfunction ()" & gt; Try it & lt; / Button & gt; & Lt; P id = "demo" & gt; & Lt; / P & gt; & Lt; / Body & gt; & Lt; / Html & gt; For performance reasons it is better to validate the value of the first comparison
before looping starts. You can break the loop by using the break
, continue
or return
keywords.
No comments:
Post a Comment