Do JavaScript arrays have an equivalent of Python’s “if a in list”?
Since ES6, it is recommended to use includes()
instead of the clunky indexOf()
.
var my_array = ['a', 'b', 'c'];
my_array.includes('a'); // true
my_array.includes('dd'); // false
var my_array = ['a', 'b', 'c'];
alert(my_array.indexOf('b'));
alert(my_array.indexOf('dd'));
if element not found, you will receive -1
var IN = function(ls, val){
return ls.indexOf(val) != -1;
}
var my_array = ['a', 'b', 'c'];
IN(my_array, 'a');