web123456

Python and JavaScript for loop traversal

Python

Python has only one for loop, which generally refers to for in, while other languages ​​are divided into for and for in

for i in [1,'a',2,'b',3]:
    print(i)

dict = {'a':1,'b':'zs','c':'ls'}
for i in dict:
    print(dict[i])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Python is very convenient when traversing sequences. Lists, ancestors, dictionary tables, collections, and strings can be traversed directly using a for loop.
All of which can be traversed with for loops are called iterable objects


JavaScript

Temporary variable i needs to be defined with keyword var

Iterate over the array:

For traversalArrayUse i++ or i- to control the number of loops, and traverse a set of incremental or decreasing numbers as the subscript of the array
Get every value in the array using the subscript index

var abc = [1,'a',2,'b',3]
for(var i=0; i<abc.length; i++){
    alert(abc[i])
}
  • 1
  • 2
  • 3
  • 4

for in

var abc = [1,'a',2,'b',3]
for(var i in abc){
    alert(abc[i])
}
  • 1
  • 2
  • 3
  • 4

Traversing the object:

It usually uses for in

var obj = {a:1,b:'Li Si',c:3,d:'Zhang San'}
for(var name in obj){
    alert(obj[name])
}
  • 1
  • 2
  • 3
  • 4

It will be very troublesome to traverse objects with for loops

var obj = {a:1,b:'Li Si',c:3,d:'Zhang San'}
for(var i=0; i<abc.length; ????){
    alert(obj[????])
}
  • 1
  • 2
  • 3
  • 4

for(var i=0; i<abc.length; i++){
}Python equivalentfor i in range(0, len(abc)):It's obvious that Python is more elegant
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8