Do JavaScript arrays have the equivalent of Pythons "if a in list"?

If I have a list in Python, I can check if the given value is in it using the in operator:

 >>> my_list = ['a', 'b', 'c'] >>> 'a' in my_list True >>> 'd' in my_list False 

If I have an array in JavaScript like

 var my_array = ['a', 'b', 'c']; 

Can I check if the value in it is similar to the Pythons in operator, or do I need to loop through an array?

+6
source share
2 answers
 var my_array = ['a', 'b', 'c']; alert(my_array.indexOf('b')); alert(my_array.indexOf('dd')); 

If the item is not found, you will get -1

+9
source
 var IN = function(ls, val){ return ls.indexOf(val) != -1 ? true : false; } var my_array = ['a', 'b', 'c']; IN(my_array, 'a'); 
+1
source

Source: https://habr.com/ru/post/897458/


All Articles