Do JavaScript arrays have an equivalent of Python’s “if a in list”?
Question:
If I have a list in Python, I can check whether a 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, e.g.
var my_array = ['a', 'b', 'c'];
Can I check whether a value is in it in a similar way to Python’s in
operator, or do I need to loop through the array?
Answers:
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');
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
The most current way with es6 would be the follow:
let myArray = ['a', 'b', 'c'];
console.log(myArray.includes('a'))
this will return true or false
If I have a list in Python, I can check whether a 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, e.g.
var my_array = ['a', 'b', 'c'];
Can I check whether a value is in it in a similar way to Python’s in
operator, or do I need to loop through the array?
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');
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
The most current way with es6 would be the follow:
let myArray = ['a', 'b', 'c'];
console.log(myArray.includes('a'))
this will return true or false