Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript equivalent to Python's for loops?

So I was dissapointed to find out that JavaScript's for ( var in array/object) was not equivalent to pythons for var in list:.

In JavaScript you are iterating over the indices themselves e.g.

0, 
1,
2,
... 

where as with Python, you are iterating over the values pointed to by the indices e.g.

"string var at index 0", 
46, 
"string var at index 2",
["array","of","values"],
...

Is there a standard JavaScript equivalent to Python's looping mechanism?

Disclaimer:

I am aware that the for (var in object) construct is meant to be used to iterate over keys in a dictionary and not generally over indices of an array. I am asking a specific question that pertains to use cases in which I do not care about order(or very much about speed) and just don't feel like using a while loop.

like image 732
Luke Avatar asked Jan 15 '15 16:01

Luke


People also ask

Are there for loops in JavaScript?

JavaScript supports different kinds of loops: for - loops through a block of code a number of times. for/in - loops through the properties of an object. for/of - loops through the values of an iterable object.

What can I use instead of for loop in JavaScript?

Use map() instead of for() loops Before I get started, this is going to teach you how the . map() function works. If you only have knowledge of for() loops in JavaScript, this article will require you to understand the Arrow Function Expression syntax (a.k.a. “fat arrow” functions).

What is the best alternative to a for loop in Python?

Map() Function in Python The map() function is a replacement to a for a loop. It applies a function for each element of an iterable.

Does JavaScript have range function like Python?

Definition of JavaScript Range. JavaScript Range is a function that is supported by JavaScript in order to return all the integer and its value from starting to the ending while traversing from start index to the end index.


2 Answers

In the next version of ECMAScript (ECMAScript6 aka Harmony) will be for-of construct:

for (let word of ["one", "two", "three"]) {
  alert(word);
}

for-of could be used to iterate over various objects, Arrays, Maps, Sets and custom iterable objects. In that sense it's very close to Python's for-in.

like image 93
phadej Avatar answered Oct 14 '22 23:10

phadej


for an array the most similar is the forEach loop (of course index is optional)

[1,2,3,4,].forEach(function(value,index){
  console.log(value);
  console.log(index);
});

So you will get the following output:

1
0
2
1
3
2
4
3
like image 41
Francesco Avatar answered Oct 14 '22 21:10

Francesco