


Summary of usage of for, for in, for of, and forEach in JavaScript (with code)
This article brings you a summary of the usage of for, for in, for of, and forEach in JavaScript (with code). It has certain reference value. Friends in need can For reference, I hope it will be helpful to you.
In JavaScript, we often need to use loop iteration methods to operate array objects, etc. Common loop methods include for, for in, for of, forEach, etc.
1.for loop
The for loop is the most basic and common type of loop. It requires three expressions in parentheses, separated by semicolons, and the last one is A curly braced block statement.
for (var i = 0; i <p><strong>Statements in the for loop</strong></p><p><strong>continue</strong> statement is used to jump out of this loop, but will continue to execute subsequent loops. The <br><strong>break</strong> statement is used to end the loop, and subsequent loops will not be executed. <br><strong>return</strong> cannot be used to jump out of a for loop. The return statement can only appear in the function body. It will terminate the execution of the function and return a specified value. </p><p><strong>Problems encountered when using for loops</strong></p><p>You may encounter using an asynchronous operation in a for loop, which is also a very common interview question. In the following scenario, you need to request a batch of username data with IDs from 0 to 9, and put the ID as the key and the name as the value into an object. The code may be like this</p><pre class="brush:php;toolbar:false">var users = {}; for (var i = 0; i { users[i] = res.name; }); }
In the end, the data result of the users object is not what we thought, but {10: 'The last user name returned by the request'}
. This is because of the asynchronous request. Due to the event queue mechanism, the for loop will be fully executed first, while the asynchronous request will be completed in an uncertain time later, and the call to the then method is queued behind the event queue. At this time, at any time The i
variable in a then method has been incremented to equal to 10 in the last loop. When the then method is continuously called, the value of the users
object key 10 will be constantly rewritten. until the last request is completed.
Use let block-level scope to solve
var users = {}; for (let i = 0; i { users[i] = res.name; }); }
The incrementing variable i can be solved by declaring it using let
. The let statement declares a local variable of block-level scope. It takes There is a block in the brackets. Each loop uses the variables in the block-level scope. It can be seen that the blocks in each loop are isolated from each other, and the variables will only take effect within this scope.
Use function closure scope to solve
var users = {}; for (var i = 0; i { users[j] = res.name; }); }()); }
We wrap the asynchronous method in an immediate execution function, and use the variables declared by var j
to undertake it in the function# The value of the ##i variable, because the immediate execution function forms a closure scope, the variable
j exists independently in each scope.
var users = {};
for (var i = 0; i {
users[value] = res.name;
});
}(i));
}
Copy after login
Pass the variable var users = {}; for (var i = 0; i { users[value] = res.name; }); }(i)); }
i as a parameter of the immediately executed function. The parameters also have their own scope. Function parameters are only in the function It works internally and is a local variable.
Object.defineProperty method to define whether an object property can be enumerated.
enumerable value of the property. Enumerability determines whether this attribute can be traversed by for...in search. The object's
propertyIsEnumerable method can determine whether the object contains a certain property and return whether the property is enumerable.
Built-in methods and properties such as Object, Array, Number, etc. are all non-enumerable
const obj = {}; Object.defineProperty(obj, 'city', {value: '北京', enumerable: false}); const isEnumerable = obj.propertyIsEnumerable('city'); console.log(obj); // {city: "北京"} console.log(isEnumerable); //false
const obj = {a:1, b:2, c:3};
Object.defineProperty(obj, 'd', {value: 4, enumerable: false})
obj.__proto__ = {name: 'ricky', age: '25'}
console.log(obj)
console.log('=====for in=======')
for (var prop in obj) {
console.log(prop, obj[prop]);
}
console.log('=====Object.keys=======')
console.log(Object.keys(obj))
console.log('=====Object.getOwnPropertyNames=======')
console.log(Object.getOwnPropertyNames(obj))
console.log('=====Object.values=======')
console.log(Object.values(obj))
console.log('=====Object.entries=======')
console.log(Object.entries(obj))
Copy after login
const obj = {a:1, b:2, c:3}; Object.defineProperty(obj, 'd', {value: 4, enumerable: false}) obj.__proto__ = {name: 'ricky', age: '25'} console.log(obj) console.log('=====for in=======') for (var prop in obj) { console.log(prop, obj[prop]); } console.log('=====Object.keys=======') console.log(Object.keys(obj)) console.log('=====Object.getOwnPropertyNames=======') console.log(Object.getOwnPropertyNames(obj)) console.log('=====Object.values=======') console.log(Object.values(obj)) console.log('=====Object.entries=======') console.log(Object.entries(obj))
Output result
##We first use object literals Define an obj, then use the Object.defineProperty method to define a non-enumerable property with key d, then modify the prototype chain __proto__ and assign it two attributes: name and age.
- for in
Traverse all enumerable properties except the property named d, including properties on its prototype chain
- Object.keys
The method will return an array consisting of the object's own enumerable property names (keys), and the properties on its prototype chain are not included
- Object.getOwnPropertyNames
The method will return an array consisting of all the property names (keys) of the object, including enumerable and non-enumerable properties
- Object.values
The method will return an array consisting of the values (values) of the object's own enumerable properties
- Object.entries
The method will return an array consisting of key-value pairs (key and value) of the object's own enumerable properties
for in会循环所有可枚举的属性,包括对象原型链上的属性,循环会输出循环对象的key,如果循环的是一个数组则会输出下标索引(index)。
in 运算符
in 运算符测试一个对象其自身和原型链中是否存在该属性。
const obj = {name: 'ricky'}; Object.defineProperty(obj, 'city', {value: '北京', enumerable: false}) obj.__proto__ = {age: '25'} console.log('name' in obj); // true console.log('city' in obj); // true console.log('age' in obj); // true console.log('sex' in obj); // false
for of(es6) 循环可迭代对象
for of循环可迭代对象(包括 Array,Map,Set,String,TypedArray,类数组的对象(比如arguments对象、DOM NodeList 对象)、以及Generator生成器对象等)。
const array = [{a: 1}, {b: 2}, {c: 3}]; array.name = 'ricky'; console.log(array) console.log('=====for of=======') for (var prop of array) { console.log(prop); } console.log('=====for in=======') for (var prop in array) { console.log(prop); }
for of 与 for in 不同处
与for in不同的是,for of不能循环普通对象({key: value})
for of不会将循环对象中自定义的属性内容循环出来
for in 是遍历键名(key或index),而for of是遍历键值(value)。
forEach、map 循环
forEach() 方法对数组的每个元素执行一次提供的函数,其中函数有三个参数,依次为:当前循环项的内容、当前循环的索引、循环的数组。
const array = ['a', 'b', 'c']; array.forEach(function(value, index, data) { console.log(value, index, data); }); // 输出 // a 0 ["a", "b", "c"] // b 1 ["a", "b", "c"] // c 2 ["a", "b", "c"]
map() 方法会依次循环每一项,并且返回结果映射组成一个新的数组。
const array = [1, 2, 3]; const newArray = array.map(function(value, index, data) { return value * 2; }); console.log(newArray); //输出 [2, 4, 6]
使用forEach、map不能中断循环,方法会将每项内容都执行完成才会结束循环。
使用every或 some 提前结束循环
every循环当返回false时循环即会结束, some方法在循环返回true时结束循环,利用这个特性使用every和some方法都可以跳出循环。
const arr = [1, 2, 3, 4, 5]; arr.every(function(value){ console.log(value); if(value === 3) { //every 循环当返回false时结束循环 return false; } return true //every 循环需要返回true,没有返回值循环也会结束 }); arr.some(function(value){ console.log(value); if(value === 3) { //some 循环当返回true时结束循环 return true; } });
The above is the detailed content of Summary of usage of for, for in, for of, and forEach in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
