This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

JavaScript learning – special symbols – bit operators, JavaScript learning – logical operators – short circuit? [JavaScript learning – arrow function],

In this article, we’ll continue learning about JavaScript – ES6’s new loop statement for/of

JavaScript – ES6 added: for/of

We are all familiar with the for loop. The new for/of statement in ES6 also has the keyword for, but this for is a completely different loop from the regular for loop.

For /in/for/in/for/in

for/of

The for/of loop is used to iterate over an iterable! Iterable objects such as arrays/strings/sets/maps are groups or batches of elements that can be iterated over to retrieve each element.

Here’s the simplest little example: Iterate over a numeric array summation problem

const arr = [1.2.3.5.6.9.8.1],
  sum = 0
for (let item of arr) {
  sum += item
}
console.log(sum) / / = = > 35
Copy the code

We can see from the example above that the for/of loop is very similar to the for loop. The for keyword is followed by a pair of parentheses containing how to loop (i.e. the condition of the loop), followed by a curly brace — the body of the loop;

In the above code, the elements in the ARR are traversed once, that is, each element is run once. After the body of the loop completes, the next element of the array is assigned to the element variable. Iterate from start to finish

For/of and objects

The above code iterates through arrays through for/of, but what about objects?

Objects (by default) cannot iterate. TypeError is thrown if you try to do a for/of traverse of a regular object at runtime.

If we want to iterate over an Object, we can use object. keys to get the property keys of the Object and return an array of the property names of the Object. You can then iterate over it using for/of.

let obj = { aa: 1.bb: 2.cc: 3.dd: 5 }
let objProArr = Object.keys(obj)
let res = ' '
for (let key in objProArr) {
  res += key
}
console.log(res) // aabbccdd
Copy the code