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 trialKip Yin
4,847 PointsHow to directly loop over array items?
In Python, it is possible to iterate through items directly, not just through their indices:
myList = list('abcd')
for x in myList:
print(x)
This would print the letters a
, b
, c
, d
, which are all items in myList
.
How can I achieve this in Javascript?
Also, is list comprehension possible in JS? In Python,
myList = [2*x for x in range(10)]
would create a list of even numbers between 0
and 20
.
What about in JS?
1 Answer
Thomas Nilsen
14,957 PointsIf you don't want to use indices you can do this:
const str = "this is a test"
str.split().forEach(l => console.log(l))
closest you get to list comprehensions (that I can think of), is this:
console.log([...Array(10)].map((_, i) => i * 2));
Kip Yin
4,847 PointsKip Yin
4,847 PointsThanks again! lol
Kip Yin
4,847 PointsKip Yin
4,847 PointsWhy can't you just do
i => i * 2
inmap
?Kip Yin
4,847 PointsKip Yin
4,847 PointsI think I got it... Just watched a video on prototypes.