Detailed introduction of for and of for and in in JavaScript

  • 2021-12-05 05:09:08
  • OfStack

Directory

In JavaScript In, for There are several common ways to write a loop

The first most conventional writing:


nums = [1,2,3,4]

for (let i=0; i<nums.length; i++){
    console.log(nums[i])
}

Type 2:

Type 2 for/of Writing, yes ES6 At the beginning, some syntax can directly iterate out every element in the array, without obtaining the element through the index position of subscript. In fact, as long as it is an iterative object, it can be used for/of .


for (let item of nums){
    console.log(item)
}

Type 3:

The third way of writing for/in Writing, unlike for/of Must be an iterable object, for/in You can iterate over any object. The property name of the loop iteration object. If it is an array, the iterative value is the subscript index of the array, and the original one for It's one kind.


let p = {name:"zhang", age:10}

for(let key in p){
    console.log(p[key])
}

Output:

zhang
10


for (let index in nums){
    console.log(nums[index])
}


for/in You can't enumerate all the attributes of iteration objects, for example, symbol attributes can't be enumerated

for/of And for/in When defining variables, you can also use const Keyword, const Declares a constant value during a loop iteration.


Related articles: