Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDan Oswalt
23,438 PointsJS equivalent of Python's easy way of cycling through iterables....
In Python, it's fantastically easy to search for a match by cycling through things in anything that's iterable:
if letter in 'abcdef':
print(letter)
if item in itemlist:
print(item)
In plain JS, is there a standard pattern for looking for a match that is less verbose than something like:
for(var index = 0; index <= list.length; i += 1) {
if(list[index] === item) {
console.log(item);
break;
}
}
?
2 Answers
Michael Hulet
47,912 PointsYou could use the indexOf
method to do that. If it return
s -1
, it isn't in the list. Otherwise, it tells you where in the list it is. This should work:
if(array.indexOf(thing) >= 0){
// It's in the array
}
else{
// It's not in the array
}
Dan Oswalt
23,438 PointsOh right, thank you, knew there was a better way.