In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use six kinds of For loops in JS". In daily operation, I believe many people have doubts about how to use six kinds of For loops in JS. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "how to use six kinds of For loops in JS". Next, please follow the editor to study!
For loops are most frequently used in development. When the front and back end data interact with each other, the common data types are arrays and objects. For traversal is often used when dealing with objects and arrays, so it takes a few minutes to thoroughly understand these five for loops before leaving work. They are:
For
For... In
For... Of
For await.. Of
ForEach
Map
1. Introduction of each for 1. For
For loop is the earliest and most widely used traversal, which can satisfy the vast majority of traverses. You can traverse arrays, objects, and strings, for example:
/ / traversal array 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 是在 ES5 中新增的,以任意顺序迭代一个对象的除Symbol以外的可枚举属性,包括继承的可枚举属性。 // 遍历数组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、for ... of for ... of 语句在可迭代对象(包括 Array、Map、Set、String、TypedArray、arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。 // 迭代 Arrayvar arr = [1, 2, 3]for (var val of arr ){ console.log(val);// 1 2 3}//迭代 Stringlet 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}// 迭代 Setlet set = new Set([1,2,3,2,1])for (let val of set) { console.log(val)// 1 2 3}4、for await...of 创建一个循环,该循环遍历异步可迭代对象以及同步可迭代对象,包括内置的 String、Array,类数组对象(arguments 或 nodeList),TypedArray, Map, Set 和用户定义的异步/同步迭代器。它使用对象的每个不同属性的值调用要执行的语句来调用自定义迭代钩子。 类似于 await 运算符一样,该语句只能在一个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 是ES5版本发布的,按升序为数组中含有效值的每一项执行一次回调函数,那些已删除或者未初始化的项将被跳过(例如在稀疏数组上),一般认为是 普通for循环 的加强版。 // 遍历数组var arr = [1, 2, 3]arr.forEach((item, index) =>{console.log (index); / 012 console.log (item); / / 123}) / / traversal object var obj = {job: 'web worker', name:' frontend code goddess'} var keys = Object.keys (obj) keys.forEach ((key) = > {console.log (key) / / job name console.log (obj [key]) / / web worker frontend code goddess}) 6, map
Traversal returns a new array, and the result of the new array is the value returned after each element in the original array calls the provided function once.
/ / traversal array var arr = [1, 2, 3] let newArr = arr.map ((item) = > item * 2) console.log (newArr); / / [2jing4jing6] 2.Differences between multiple for 1. Differences in usage scenarios
For loop is the earliest and most primitive loop traversal statement. For defines a variable and iterates according to conditions, usually the length of the array. When the length is exceeded, the loop is stopped. Generally, the loop is traversed by an array or class array. When traversing an object, because the object has no length, use Object.keys () to get all the properties of the object and return it as an array.
For / in is mainly used to traverse the enumerable properties on the object, including the properties on the prototype object, traversing in any order, traversing the object to get the key value of the attribute, traversing the array, and the subscript of the array as the key value.
For / of is used to traverse the data of iterable objects, including Array, Map, Set, String, TypedArray, arguments objects, and so on.
For await...of is used to traverse asynchronous iterable objects, and this statement can only be used within an async function.
ForEach is an updated version of for, which is easier to use and carries more parameters, but it is essentially a loop of an array. Each element performs a callback without changing the original array.
Map performs 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 the loop, others do not support it.
For await... Of can support asynchronous operations, others do not.
For pure object traversal, for... In enumeration is more convenient.
For array traversal, if you do not need an index, you can directly use for...of to get the value, and you can also support break or return; if you also need an index, forEach is more appropriate, but does not support return.
If you are mapping one array to another, map is the most appropriate.
3. Performance difference
When the test environment and test data conditions are consistent, the performance order is as follows:
For > for of > forEach > map > for in.
For has the fastest performance because it has no additional function calls and context.
For... Of has the data structure of the iterator interface, which can be used to iterate over members and read key values directly.
ForEach is the syntactic sugar of for, and there are many parameters and context, so it will be slower.
Map because it returns a brand new array of equal length, the performance overhead caused by array creation and assignment is high.
For...in has the worst performance, because it needs to enumerate all the attributes of the object, there is a conversion process, and it is expensive.
III. The use of for
In project development, we should choose an appropriate for traversal according to the actual needs. Here are some suggestions for use:
If you need to map the data to another array, such as the corresponding Boolean value, it is recommended to use map, the original array will not be modified, and the syntax is simple.
For array traversal, you can use for, forEach, or for...of.
When traversing pure objects, it is recommended to use for... In .
If you need to traverse the iterator, it is recommended that you use for... Of .
If you are filtering an array that meets the criteria, use fillter.
At this point, the study on "how to use six For loops in JS" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.