Find JavaScript array elements [duplicate]

0

I would like to create a input that receives a value entered by the user and that when I click a button it executes a function that checks if the value entered exists in my array and if there is an index it is contained.

var vetor = [1, 2, 3];<br>
var elemento = document.getElementById("verifica").value;

<.input type='text' id="verifica">
    
asked by anonymous 05.04.2018 / 08:02

2 answers

1

Use a loop to iterate the Array elements, and if any value matches the value of the input, return the index of that element.

    var vetor = [1, 2, 3, 4, 5];

    function checar(){
      valInput=document.getElementById("verifica").value;
      for (var i = 0; i < vetor.length; ++i) {
          if (vetor[i] == valInput) {
              index = i;
              console.log(index);
              break;
          }
      }
    }
    <input id="verifica" type="text">
    <button type="submit" onclick="checar()">Verificar</button>
  

You can use findIndex () , but it does not work in IE 11 and earlier

    
05.04.2018 / 14:17
1

You can do this: The indexOf method looks for the value ( val ) in the vector ( vetor ) if it finds it returns the position of the element in the array. If it does not find the value it returns -1. An array starts at position 0. I made a sum in the result to increase the positions in a house. So then the positions will be greater than zero.  It is important to note the function parseInt() it turns into integer what is passed as parameter. That is useful in this example because we want to perform comparisons and operations between integers.

var verifica = function(){
    var vetor = [1, 2, 3];
    var val = document.getElementById("verifica").value;
   
    var a = vetor.indexOf(parseInt(val));

    if(a === -1){

      alert("Valor não encontrado")

    }else if(a !== -1){

      alert("Valor encontrado na posição " + (a+1));

    }

  }
 <input id="verifica" type="text" >
  <button type="submit" onclick="verifica()">Verificar
  </button>
    
05.04.2018 / 08:40