Home > Article > Web Front-end > 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.
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.
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)); }
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); //falsefor...in can traverse enumerable but objects, including not itself But properties exist on the prototype chain.
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.
Traverse all enumerable properties except the property named d, including properties on its prototype chain
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
The method will return an array consisting of all the property names (keys) of the object, including enumerable and non-enumerable properties
The method will return an array consisting of the values (values) of the object's own enumerable properties
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 运算符测试一个对象其自身和原型链中是否存在该属性。
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循环可迭代对象(包括 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 in不同的是,for of不能循环普通对象({key: value})
for of不会将循环对象中自定义的属性内容循环出来
for in 是遍历键名(key或index),而for of是遍历键值(value)。
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循环当返回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!