详解JS中常见的5 种 for 循环
For loops are the most commonly used in daily development, especially when interacting with front-end and back-end data. The most common data types are arrays and objects, and when handling objects and arrays, for loops are frequently used. Therefore, it is essential to thoroughly understand the five types of for loops. They are as follows:
- for
- for...in
- for...of
- for await...of
- forEach
- map
One: Introduction to Each For Loop
1. for
The for loop is the earliest and most widely used iteration method. It can satisfy most iteration needs. It can iterate over arrays, objects, and strings. Example:
// Iterate over an array
var arr = [1, 2, 3];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// Iterate over an object
var obj = {
job: 'web worker',
name: '前端代码女神'
};
for (var i = 0, keys = Object.keys(obj); i < keys.length; i++) {
console.log(obj[keys[i]]);
}
// Iterate over a string
let str = 'abc';
for (var i = 0; i < str.length; i++) {
console.log(str[i]);
}
2. for...in
The for...in loop was introduced in ES5, and it iterates over the non-symbol enumerable properties of an object, including inherited ones.
// Iterate over an array
var arr = [1, 2, 3];
for (var i in arr) {
console.log(i); // 0 1 2
console.log(arr[i]); // 1 2 3
}
// Iterate over an object
var obj = {
job: 'web worker',
name: '前端代码女神'
};
for (var key in obj) {
console.log(key); // job name
console.log(obj[key]); // web worker 前端代码女神
}
// Iterate over a string
let str = 'abc';
for (var i in str) {
console.log(i); // 0 1 2
console.log(str[i]); // a b c
}
3. for...of
The for...of statement creates an iteration loop on iterable objects (including Array, Map, Set, String, TypedArray, arguments object, etc.), calling custom iteration hooks and executing statements for each value of different properties.
// Iterate over an array
var arr = [1, 2, 3];
for (var val of arr) {
console.log(val); // 1 2 3
}
// Iterate over a string
let str = 'abc';
for (var val of str) {
console.log(val); // a b c
}
// Iterate over TypedArray
let iterable = new Uint8Array([0x00, 0xff]);
for (let value of iterable) {
console.log(value); // 0 255
}
// Iterate over a 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
}
// Iterate over a 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
The for await...of loop iterates over asynchronous iterable objects and synchronous iterable objects, including built-in String, Array, array-like objects (arguments or nodeList), TypedArray, Map, Set, and user-defined async/sync iterators. It calls custom iteration hooks using the values of each different property. This statement can only be used within an async function, similar to the await operator.
async function* asyncGenerator() {
var i = 0;
while (i < 3) {
yield i++;
}
}
(async function () {
for await (let num of asyncGenerator()) {
console.log(num); // 0 1 2
}
})();
5. forEach
The forEach method was introduced in ES5, and it executes a callback function for each valid value in an array. Elements that have been deleted or not initialized are skipped (e.g., in sparse arrays). It is generally considered an enhanced version of the standard for loop.
// Iterate over an array
var arr = [1, 2, 3];
arr.forEach((item, index) => {
console.log(index); // 0 1 2
console.log(item); // 1 2 3
});
// Iterate over an object
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. map
During iteration, it returns a new array, where the result is the value obtained by calling the provided function on each element of the original array.
// Iterate over an array
var arr = [1, 2, 3];
let newArr = arr.map((item) => item * 2);
console.log(newArr); // [2, 4, 6]
Two: Differences Between Multiple For Loops
1. Usage Scenario Differences
The for loop is the earliest and most primitive iteration method. It defines a variable inside the loop and iterates based on conditions, typically using the length of an array. It stops when the condition is false. It is generally used for arrays or array-like objects. When iterating over objects, since objects do not have a length, Object.keys() is used to get all properties, returned as an array. The for...in loop is mainly used to iterate over enumerable properties of objects, including properties on prototype objects, and iterates in any order. When iterating over objects, it retrieves the property keys, and the index of the array is used as the key. The for...of loop is used to iterate over iterable objects, including arrays, Maps, Sets, Strings, TypedArrays, and argument objects. The for await...of loop is used to iterate over asynchronous iterable objects, and this statement can only be used within an async function. The forEach method is an enhanced version of the for loop, with more parameters and context, but it is still an array iteration. The map method applies a callback function to each element of the original array and returns a new array, without modifying the original array.
2. Functional Differences
The forEach and map methods do not support breaking out of the loop, while others do not. The for await...of method supports asynchronous operations, while others do not. For pure objects, the for...in loop is more convenient for enumeration. For array iteration, if the index is not needed, you can directly use for...of to get the value and support break or return; if the index is needed, the forEach method is more suitable, but it does not support return. If you need to map an array to another array, the map method is the most appropriate.
3. Performance Differences
Under consistent test environments and data conditions, the performance ranking is as follows: for > for...of > forEach > map > for...in. The for loop is the fastest because it does not involve additional function calls or context. The for...of statement uses data structures with an iterator interface, allowing direct access to key-value pairs. The forEach method is a syntactic sugar of the for loop, with more parameters and context, so it is slower. The map method, due to returning a new array of the same length, incurs significant performance costs during array creation and assignment. The for...in loop is the slowest, as it requires listing all object properties, involving a conversion process, which incurs significant overhead.
Three: Usage of For Loops
In project development, it is recommended to choose an appropriate for loop based on actual needs. Here are some usage suggestions:
- If you need to map data into another array, such as converting to a boolean value, recommend using the map method, which does not modify the original array and has simple syntax.
- During array iteration, you can use for, forEach, or for...of.
- When iterating over pure objects, recommend using for...in.
- If you need to iterate over an iterator, recommend using for...of.
- If you need to filter an array that meets certain conditions, use the fillter method.
