In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "for, foreach, map, for...in, for...of method case Analysis", so the editor summarizes the following contents for you. The content is detailed, the steps are clear, and it has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "for, foreach, map, for...in, for...of method example Analysis" article.
Self introduction
For
I was the first to appear in the ergodic sentence, and all of you here need to call me Grandpa. I can meet most of the needs of developers.
/ / the ergodic array let arr = [1 let 2, 3]; for (I = 0 position I)
< arr.length;i++){ console.log(i) // 索引,数组下标 console.log(arr[i]) // 数组下标所对应的元素}// 遍历对象let profile = {name:"April",nickname:"二十七刻",country:"China"};for(let i = 0, keys=Object.keys(profile); i < keys.length;i++){ console.log(keys[i]) // 对象的键值 console.log(profile[keys[i]]) // 对象的键对应的值}// 遍历字符串let str = "abcdef";for(let i = 0;i < str.length ;i++){ console.log(i) // 索引 字符串的下标 console.log(str[i]) // 字符串下标所对应的元素}// 遍历DOM 节点let articleParagraphs = document.querySelectorAll('.article >P'); for (let I = 0 name I console.log (I)) / / logs 1 country / logs 2 / logs 3) / directly outputs the elements of the array / / ergodic objects let profile = {name: "April", nickname: "27 moments", country: "China"}; let keys = Object.keys (profile) Keys.forEach (I = > {console.log (I) / the key value of the object console.log (profile [I]) / the value corresponding to the key of the object})
Map
I am also released in the ES5 version, and I can create a new array that results in the return value of each element in the original array after calling the provided function once.
Let arr = [1, 2, 3, 4, 5]; let res = arr.map (I = > I * I); console.log (res) / / logs [1, 4, 9, 16, 25]
For...in enumeration
I released it in the ES5 version. Traverses the enumerable properties of an object except Symbol in any order.
/ / traversal object let profile = {name: "April", nickname: "27 moments", country: "China"}; for (let i in profile) {let item = profile [I]; console.log (item) / / the key value of the object console.log (I) / / the value corresponding to the key of the object let arr = ['axiaojiaozhuo']; for (let i in arr) {let item = arr [I] Console.log (item) / / element console.log (I) / / index corresponding to array subscript, array subscript / / traversal string let str = "abcd" for (let i in str) {let item = str [I]; element console.log (I) / / subscript of index string corresponding to console.log (item) / / string subscript}
For...of iteration
I released it in the ES6 version. Create an iteration loop over iterable objects (including Array,Map,Set,String,TypedArray,arguments objects, and so on), call custom iteration hooks, and execute statements for the values of each different property.
/ / iterative array array let arr = ['axiomanagadhi (item)]; for (let item of arr) {console.log (item)} / / logs'apyramid / logs'blemaget / iterative string let str = "abc"; for (let value of str) {console.log (value) } / / logs'a hammer let entry of iterable / logs'b cards for / logs'c hammer / iterative maplet iterable = new Map ([["a", 1], ["b", 2], ["c", 3]] for (let entry of iterable) {console.log (entry) } / / logs ["a", 1] / / logs ["b", 2] / / logs ["c", 3] / / iterative map to get the key value for (let [key, value] of iterable) {console.log (key) console.log (value);} / / iterative setlet iterable = new Set ([1, 1, 2, 2, 3, 3)); for (let value of iterable) {console.log (value) } / / logs 1 paragraph.classList.add / logs 2 paragraph.classList.add / logs 3 paragraph.classList.add / logs 4 pick / iterative DOM node let articleParagraphs = document.querySelectorAll ('. Article > p'); for (let paragraph of articleParagraphs) {paragraph.classList.add ("paragraph"); / / add a class attribute named "paragraph" to the p tag under the class named "article" node. } / iterative arguments class array objects (function () {for (let argument of arguments) {console.log (argument);}}) (1, 2, 3); / / logs:// 1 / 2 / 3 / iterative type array let typeArr = new Uint8Array ([0x00, 0xff]); for (let value of typeArr) {console.log (value);} / / logs:// 0Uniple / 255
After the first round of self-introduction and skills presentation, we learned:
The for statement is the most primitive loop statement. Define a variable I (numeric type, which represents the subscript of the array), and accumulate I in a loop according to certain conditions. The condition is usually the length of the loop object, and when the length is exceeded, the loop is stopped. Because the object cannot judge the length, it is used with Object.keys ().
ForEach ES5 proposed. Claiming to be an enhanced version of the for statement, you can find that it is much easier to write than the for statement. But it's essentially a loop of an array. ForEach executes the callback function once for each array element. That is, the array that calls it, so the original array will not be changed. The return value is undefine.
Map ES5 proposed. The callback function is called once for each element in the original array. Generates a new array without modifying the original array itself that calls it. The return value is a new array.
For...in ES5 proposed. Traverses the enumerable properties on the object, including the properties on the prototype object, and traverses in any order, that is, in an irregular order. When traversing an array, the subscript of the array is used as a key value, and the I in this case is a string. It is built to traverse object properties and is not recommended for use with arrays.
For...of ES6 proposed. Traverses only the data of iterable objects.
Ability discrimination
As a programmer, it is far from enough to know them and identify their respective strengths and weaknesses in actual development. Use them according to local conditions, give full play to their strengths and avoid weaknesses. In order to improve the overall performance of the program is the ability.
About jumping out of the loop
If you meet certain conditions in the loop, you will jump out of the loop body, or skip the data that do not meet the conditions and continue to cycle other data. It's a demand that you often encounter. The common statements are break and continue.
Simply talk about the difference between the two, as a review.
A break statement is a statement that jumps out of the current loop and executes it.
The continue statement terminates the current loop and continues to execute the next loop
Note: forEach and map do not support jumping out of the loop body, the other three methods are supported.
Principle: if you look at the principle of forEach implementation, you will understand this problem.
Array.prototype.forEach (callbackfn [, thisArg] {}
The function passed in is the callback function here. It must be illegal to use break in the callback function, because break can only be used to jump out of the loop, and the callback function is not the body of the loop.
Using return in the callback function simply returns the result to the parent function, that is, the for loop, without ending the for loop, so return is also invalid.
The same goes for map ().
Map () chained call
The map () method can be called chained, which means it can be easily used in conjunction with other methods. For example: reduce (), sort (), filter (), etc. But other methods can't do this. The return value of forEach () is undefined, so it cannot be called chained.
/ / multiply the element by itself, and then sum it. Let arr = [1,2,3,4,5]; let res1 = arr.map (item = > item * item). Reduce ((total, value) = > total + value); console.log (res1) / / logs 55 undefined "
For...in traverses the properties on the prototype object
Object.prototype.objCustom = function () {}; Array.prototype.arrCustom = function () {}; var arr = ['a cow, 'baked,' c']; arr.foo = 'hellofor (var i in arr) {console.log (I);} / / logs// 0amp / 1 / 2 / foo// arrCustom// objCustom
However, in actual development, we do not need properties on the prototype object. In this case, we can use the hasOwnProperty () method, which returns a Boolean value indicating whether the object has a specified property in its own property (that is, whether there is a specified key). As follows:
Object.prototype.objCustom = function () {}; Array.prototype.arrCustom = function () {}; var arr = ['averse,' baked,'c']; arr.foo = 'hellofor (var i in arr) {if (arr.hasOwnProperty (I)) {console.log (I);}} / / logs// 0Gap / 1hellofor / 2mp / foo// visible array itself is still unable to get rid of. ForEach is recommended at this time.
For pure object traversal, it is more convenient to choose for..in enumeration; for array traversal, it is more appropriate if you do not need to know the index for..of iteration, because it can also be interrupted; if you need to know the index, then forEach () is more appropriate; for other string, class array, type array iteration, for..of has the upper hand. Note, however, that the lower version of the browser is compatible.
Performance
Interested readers can find a set of data to test themselves, and the article will give the results directly and explain them accordingly.
For > for-of > forEach > map > for-in
The-for loop is certainly the simplest because it does not have any additional function call stack or context
For...of can use it to iterate over members as long as it has the data structure of the Iterator interface. It reads the key value directly.
ForEach, because it's actually a little more complicated than we thought, it's actually array.forEach (function (currentValue, index, arr), thisValue) it's not the syntax sugar of an ordinary for loop, and there are a lot of parameters and contexts that need to be taken into account during execution, which may slow down performance.
Map () is the slowest because its return value is a brand new array of equal length, and the performance overhead of array creation and assignment is significant.
For...in needs to enumerate all the properties of the object, including custom added properties that can also be traversed. And the key of for...in is of String type, which has a conversion process and costs a lot of money.
The above is about "for, foreach, map, for...in, for...of method case analysis" of this article, I believe we all have a certain understanding, I hope the content shared by the editor will be helpful to you, if you want to know more related knowledge, please pay attention to the industry information channel.
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.