I have an array on JS containing numeric values:

var massiv = [ "100", "101", "456", "1000", "321" ] 

And there is a variable:

 var peremennaya = "101" 

Task: if the variable matches one of the array values, then you need to perform an action. For example:

 alert = "Нашлось 101" 

The array contains only numeric values, but they are wrapped in quotes for versatility, I think, that is, so that the script does not only compare values

 == 

but also found letter matches.

If possible, I would like to see an example with explanations of each step in the form of comments or how convenient.

  • Purely for the sake of interest: why did they consider that writing extra code with for is better than simple indexOf ? - Alexey Shimansky
  • The cycle was more practical if the variable changes. - Frontendman

3 answers 3

Using the for loop example

 var massiv = [ "100", "101", "456", "1000", "321" ] var peremennaya = "101"; for (i = 0; i < massiv.length; i++) { if (peremennaya == massiv[i]) { alert("Мы нашли "+massiv[i]) } } 

     var peremennaya = 101; var massiv = [ 100, 101, 456, 1000, 321 ]; if (massiv.indexOf(peremennaya) != -1) console.log('Массив содержит значение ' + peremennaya); 

    There is nothing to explain here. The indexOf () method returns the first index by which the given element can be found in the array or -1 if there is no such index.

    More detailed and diverse examples of the application of the method can be found at the link above.

      Here on the Orthodox js there is a special search function by criterion
      and if there is a multiple entry of the element in the array

       var peremennaya = 101 ; var massiv = [100, 101, 456, 1000, 321]; var itog = massiv.filter(item => { return item === peremennaya; // тут логика сравнения }); console.log(itog); 

      • This is filtering, not search. For a specific search you need to use Array#find . - user207618