Detailed explanation of 5 common for loops in JS

The for loop is most frequently used in daily development. When interacting with front-end and back-end data, the common data types are arrays and objects. For traversal is often used when processing objects and arrays, so you need to thoroughly understand these five types of for loops. They are:

  • for
  • for ... in
  • for ... of
  • for await .. of
  • forEach
  • map

1. Introduction to each for

1、for

The for loop is the earliest and most commonly used traversal, and can satisfy the vast majority of traversals. You can traverse arrays, objects, and strings, examples:

// 遍历数组
var arr = [1, 2, 3]
for (var i = 0; i < arr.length; i++){
  console.log(arr[i]);
}
//遍历对象
var obj = {
  job: 'web worker',
  name:'前端代码女神'
}
for (var i = 0,keys = Object.keys(obj); i< keys.length; i++){
  console.log(obj[keys[i]])
}
//遍历字符串
let str = 'abc'
for (var i = 0; i < str.length; i++){
  console.log(str[i])
}

2. for ... in
for ... in is new in ES5. It iterates the enumerable properties of an object except Symbol in any order, including inherited enumerable properties.

// 遍历数组
var arr = [1, 2, 3]
for (var i in arr ){
  console.log(i);//0 1 2
  console.log(arr[i]);//1 2 3
}
//遍历对象
var obj = {
  job: 'web worker',
  name:'前端代码女神'
}
for (var key in obj){
  console.log(key)// job name
  console.log(obj[key])// web worker  前端代码女神
}
//遍历字符串
let str = 'abc'
for (var i in str){
  console.log(i) // 0 1 2
  console.log(str[i]) // a b c
}

3. The for ... of
for ... of statement creates an iteration loop on iterable objects (including Array, Map, Set, String, TypedArray, arguments objects, etc.), calls the custom iteration hook, and for each Statements are executed for different attribute values.

// 迭代 Array
var arr = [1, 2, 3]
for (var val of arr ){
  console.log(val);// 1 2 3
}
//迭代 String
let str = 'abc'
for (var val of str){
  console.log(val) // a b c
}
// 迭代 TypedArray - 一个类型化数组,描述了一个底层的二进制数据缓冲区!
let iterable = new Uint8Array([0x00, 0xff]);

for (let value of iterable) {
  console.log(value);//0 255
}
// 迭代 Map - 对象保存键值对,能够记住键的原始插入顺序
let map = new Map([['a',1],['b',2]])
for (let key of map) {
  console.log('key',key)//['a',1] ['b',2] 
}
for (let [key,value] of map) {
  console.log(key) // a b
  console.log(value) // 1 2
}
// 迭代 Set
let set = new Set([1,2,3,2,1])
for (let val of set) {
  console.log(val)// 1 2 3
}

4. for await...of
creates a loop that traverses asynchronous iterable objects and synchronous iterable objects, including built-in String, Array, array-like objects (arguments or nodeList), TypedArray, Map, Set and user-defined Asynchronous/synchronous iterators.
It calls the custom iteration hook using the value of each different property of the object to call the statement to be executed.
Similar to the await operator, this statement can only be used inside an async function

async function* asyncGenerator() {
  var i = 0;
  while (i < 3) {
    yield i++;
  }
}
(async function () {
  for await (num of asyncGenerator()) {
    console.log(num);// 0 1 2
  }
})();

5. forEach
forEach is released in the ES5 version. It executes a callback function in ascending order for each item containing a valid value in the array. Those items that have been deleted or uninitialized will be skipped (for example, on a sparse array). It is generally considered to be An enhanced version of the ordinary for loop. 

// 遍历数组
var arr = [1, 2, 3]
arr.forEach((item, index) => {
  console.log(index);//0 1 2
  console.log(item);// 1 2 3
})
//遍历对象
var obj = {
  job: 'web worker',
  name:'前端代码女神'
}
var keys = Object.keys(obj)
keys.forEach((key) => {
  console.log(key)// job name
  console.log(obj[key])// web worker  前端代码女神
})

6.
A new array can be returned during map traversal. The result of the new array is the value returned after calling the provided function once for each element in the original array.

// 遍历数组
var arr = [1, 2, 3]
let newArr = arr.map((item) => item * 2)
console.log(newArr);//[2,4,6]

2. The difference between multiple for

1. Differences in usage scenarios

The for loop is the earliest and most primitive loop traversal statement. A variable is defined inside for and the loop is traversed according to the conditions, usually the length of the array. When the length is exceeded, the loop stops. Generally, arrays or array-like traversals are traversed.
When traversing the object, since the object has no length, use Object.keys() to get all the properties of the object and return them in the form of an array.
for / in is mainly used to traverse the enumerable properties on the object, including the properties on the prototype object, in any order. When traversing the object, the key value of the property is obtained. What is traversed is the array and the subscript of the array. As a key value.
for / of is used to traverse the data of iterable objects, including Array, Map, Set, String, TypedArray, arguments objects, etc.
for await...of is used to traverse asynchronous iterable objects. This statement can only be used inside an async function.
forEach is an upgraded version of for. It is simpler to use and carries more parameters, but its essence is still an array loop. Each element executes a callback without changing the original array.
Map executes a callback for each element of the original array and returns a new array without changing the original array.
2. Functional differences:
forEach and map do not support jumping out of loops, and others do not.
for await ... of can support asynchronous operations, but others do not.
For traversal of pure objects, the for ... in enumeration is more convenient.
For array traversal, if an index is not needed, you can directly use for...of to obtain the value, and break or return is also supported; if an index is also needed, forEach is more suitable, but return is not supported.
If one array is mapped to another array, using map is most appropriate.
3. Performance differences
When the test environment and test data conditions are consistent, the performance ranking is:
for > for of > forEach > map > for in.
for has the fastest performance because there are no additional function calls and context.
for ... of is a data structure with an iterator interface, which can be used to iterate members and read key values ​​directly.
forEach is syntactic sugar for for, and has many parameters and context, so it will be slower.
Because map returns a new array of equal length, the performance overhead caused by array creation and assignment is relatively large.
for...in has the worst performance, because it needs to enumerate all attributes of the object, requires a conversion process, and is relatively expensive.

3. Use of for

In project development, we should choose an appropriate for traversal based on actual needs. The following are some usage suggestions:
If you need to map the data into another array, such as a corresponding Boolean value, it is recommended to use map, which will not modify the original array and has simple syntax.
When traversing the array, you can use for, forEach or for...of.
When traversing pure objects, it is recommended to use for ... in.
If you need to traverse iterators, it is recommended to use for ... of.
If you are filtering arrays that meet conditions in an array, use fillter.

Guess you like

Origin blog.csdn.net/weixin_42504805/article/details/133122435