当前位置:网站首页>If I write the for loop again, I will hammer myself
If I write the for loop again, I will hammer myself
2022-06-10 13:13:00 【Lurongtao】
If I write again for loop , I'll hammer myself
Among several traversal methods for Fastest execution , It doesn't have any additional function call stack and context . But in actual development, we should combine semantic words 、 Readability and program performance , To choose which solution to use . The following term for , foreach , map ,for…in , for…of There are five methods battle.
Self introduction.
for
I was the first one to appear , All of you here need to call me Grandpa . I can meet most of the needs of developers .
// Traversal array
let arr = [1,2,3];
for(let i = 0;i < arr.length;i++){
console.log(i) // Indexes , The array subscript
console.log(arr[i]) // Elements corresponding to array subscripts
}
// Traversing objects
let profile = {name:"April",nickname:" Twenty seven quarters ",country:"China"};
for(let i = 0, keys=Object.keys(profile); i < keys.length;i++){
console.log(keys[i]) // The key value of the object
console.log(profile[keys[i]]) // The value corresponding to the key of the object
}
// Traversal string
let str = "abcdef";
for(let i = 0;i < str.length ;i++){
console.log(i) // Indexes The subscript of a string
console.log(str[i]) // The element corresponding to the string subscript
}
// Traverse DOM node
let articleParagraphs = document.querySelectorAll('.article > p');
for(let i = 0;i<articleParagraphs.length;i++){
articleParagraphs[i].classList.add("paragraph");
// to class be known as “article” Node under p Add a tag named “paragraph” class attribute
}
forEach
I am a ES5 Version released . Execute once in ascending order for each item in the array that contains valid values callback function , Items that have been deleted or uninitialized will be skipped ( For example, on a sparse array ). I am a for An enhanced version of the loop .
// Traversal array
let arr = [1,2,3];
arr.forEach(i => console.log(i))
// logs 1
// logs 2
// logs 3
// Directly output the elements of the array
// Traversing objects
let profile = {name:"April",nickname:" Twenty seven quarters ",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 ES5 Version released , I can create a new array , The result of the new array is 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 am a ES5 Version released . Traverse the division of an object in any order Symbol Enumerable properties other than .
// Traversing objects
let profile = {name:"April",nickname:" Twenty seven quarters ",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
// Traversal array
let arr = ['a','b','c'];
for(let i in arr){
let item = arr[i];
console.log(item) // Elements corresponding to array subscripts
console.log(i) // Indexes , The array subscript
// Traversal string
let str = "abcd"
for(let i in str){
let item = str[i];
console.log(item) // The element corresponding to the string subscript
console.log(i) // Indexes The subscript of a string
}
for…of iteration
I am a ES6 Version released . In iteratable objects ( Include Array,Map,Set,String,TypedArray,arguments Objects, etc. ) Create an iteration loop on , Call the custom iteration hook , And execute statements for the values of each different property .
// Iterative array
let arr = ['a','b','c'];
for(let item of arr){
console.log(item)
}
// logs 'a'
// logs 'b'
// logs 'c'
// Iteration string
let str = "abc";
for (let value of str) {
console.log(value);
}
// logs 'a'
// logs 'b'
// logs 'c'
// iteration map
let 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]
// iteration map Get key value
for (let [key, value] of iterable) {
console.log(key)
console.log(value);
}
// iteration set
let iterable = new Set([1, 1, 2, 2, 3, 3,4]);
for (let value of iterable) {
console.log(value);
}
// logs 1
// logs 2
// logs 3
// logs 4
// iteration DOM node
let articleParagraphs = document.querySelectorAll('.article > p');
for (let paragraph of articleParagraphs) {
paragraph.classList.add("paragraph");
// to class be known as “article” Node under p Add a tag named “paragraph” class attribute .
}
// iteration arguments Class array object
(function() {
for (let argument of arguments) {
console.log(argument);
}
})(1, 2, 3);
// logs:
// 1
// 2
// 3
// Iteration type array
let typeArr = new Uint8Array([0x00, 0xff]);
for (let value of typeArr) {
console.log(value);
}
// logs:
// 0
// 255
After the first round of self introduction and skill display , We learned that :
- for Statement is the most primitive circular statement . Define a variable i( Numeric type , Indicates the subscript of an array ), Under certain conditions , Yes i Perform cyclic accumulation . The condition is usually the length of the loop object , When the length is exceeded, the cycle stops . Because the object cannot determine the length , So match it Object.keys() Use .
- forEach ES5 Put forward . Claim to be for Enhanced version of statement , It can be found that it is better than for The sentence is much simpler in writing . But it's essentially an array loop .forEach Execute once per array element callback function . That is, the array that calls it , therefore , It doesn't change the original array . The return value is undefine.
- map ES5 Put forward . Call each element in the original array once in order callback function . Generate a new array , Do not modify the original array itself that calls it . The return value is the new array .
- for…in ES5 Put forward . Traversing enumerable properties on an object , Including properties on prototype objects , And traverse in any order , That is, the order is not fixed . When traversing an array, take the subscript of the array as the key value , At this time i It's a string . It is built to traverse object properties , Not recommended with arrays .
- for…of ES6 Put forward . Only traverse the data of iteratable objects .
Ability screening
As a programmer , Just knowing them is not enough , Identify their strengths and weaknesses in actual development . Use them according to local conditions , Foster strengths and circumvent weaknesses . To improve the overall performance of the program is the ability .
About jumping out of the loop
If certain conditions are met in the loop, it will jump out of the loop body , Or skip the unqualified data and continue to cycle other data . It's a common need . The commonly used statement is break And continue.
Simply say the difference between the two , Just review .
- break Statement is to jump out of the current loop , And execute the statement after the current loop ;
- continue Statement is to terminate the current loop , And continue with the next loop ;
Be careful :forEach And map It is not supported to jump out of the loop body , The other three methods support .
principle : see forEach Realization principle , Will understand this problem .
Array.prototype.forEach(callbackfn [,thisArg]{
}
Incoming function Is the callback function here . Use... In the callback function break It must be illegal , because break Can only be used to jump out of a loop , The callback function is not a loop body .
Use... In callback functions return, Just return the result to the parent function , That's it for In circulation , It's not over for loop , therefore return It's also ineffective .
map() Empathy .
map() call chaining
map() Methods can be called chained , This means that it can be easily combined with other methods . for example :reduce(), sort(), filter() etc. . But other methods can't do this .forEach() The return value of undefined, So you can't chain call .
// Multiply the element by itself , And then sum it up .
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 It will traverse the properties on the prototype object
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
var arr = ['a', 'b', 'c'];
arr.foo = 'hello
for (var i in arr) {
console.log(i);
}
// logs
// 0
// 1
// 2
// foo
// arrCustom
// objCustom
However, in actual development , We don't need properties on the prototype object . In this case we can use hasOwnProperty() Method , It will return a Boolean value , Indicates whether the specified property exists in the object's own property ( That is to say , Is there a specified key ). as follows :
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
var arr = ['a', 'b', 'c'];
arr.foo = 'hello
for (var i in arr) {
if (arr.hasOwnProperty(i)) {
console.log(i);
}
}
// logs
// 0
// 1
// 2
// foo
// It can be seen that the properties of the array itself can't get rid of . Recommended at this time forEach
For traversal of pure objects , choice for…in Enumeration is more convenient ; For array traversal , If you don't need to know the index for…of Iteration is more appropriate , Because it can also interrupt ; If you need to know the index , be forEach() More appropriate ; For other strings , An array of class , Iteration of type array ,for…of More advantage, more advantage . But note that the lower version of the browser is the compatibility .
performance
Interested readers can find a set of data to test by themselves , The article gives the result directly , And make corresponding explanations .
for > for-of > forEach > map > for-in
- for The loop is of course the simplest , Because it doesn't have any additional function call stack and context ;
- for…of As long as it has Iterator Data structure of the interface , You can use it to iterate over members . It directly reads the key value .
- forEach, Because it's actually more complicated than we thought , It's actually array.forEach(function(currentValue, index, arr), thisValue) It's not ordinary for Cyclic grammar sugar , There are also many parameters and contexts that need to be taken into account when executing , It can slow down performance here ;
- map() The slowest , Because its return value is a new array of equal length , The performance overhead of array creation and assignment is very high .
- for…in You need to enumerate all the properties of the object , Including custom added attributes, you can also traverse to . And for…in Of key yes String type , There's a transformation process , It costs a lot .
summary
In actual development, we should combine semantic words 、 Readability and program performance , To choose which solution to use .
If you need to map an array to another array according to some rule , You should use map.
If you need a simple traversal , use forEach perhaps for of.
If you need to traverse the iterator , use for of.
If you need to filter out qualified items , use filterr.
If you need to map to a new array according to the rules first , Then filter according to the conditions , Then use one map Add one more filter.
All in all , Adjust measures to local conditions , Change from time to time . Don't pursue performance too much , Ignoring semantics and readability . Under your rule , they 5 Each can only give full play to their strengths , No one wants to dominate .
- End -
* Lu Rongtao front-end learning exchange Q Group 858752519
Add group notes :CSDN recommend 
边栏推荐
- 2022 ciscn preliminary PWN complete WP
- 【FLinlk】Flink小坑之kerberos动态认证
- colmap源码阅读笔记[1] threading.cc
- Tensorflow2.0 advanced learning - image (11)
- Binary XML file line 96: error inflating class & lt; unknown&gt;
- 六石编程学:以文字处理的位置,谈谈命名
- Asynchronous export of Excel
- WTO MC12 restart agenda focuses on global economic recovery
- 从解读 BDC 自动生成的代码谈起,讲解 SAPGUI 的程序组成部分
- VDO-SLAM源码阅读笔记[2] local optimization和global optimization
猜你喜欢

Count the number and average value of natural numbers whose sum of bits within 100 is 7

蔚来:“拿捏”了数据,“扭捏”着未来

百度程序员删库被判9个月,手机号一键解绑功能发布,推特再向马斯克妥协,今日更多大新闻在此...

Don't mistake "it informatization" for "super project"

Case sharing and implementation introduction of SAP field service management and wechat integration

Ant financial services Yang Jun: evolution of ant data analysis platform and application of data analysis methods
![[deep learning] the credit card fraud anomaly detection based on the deep learning autoencoder is very effective](/img/69/505707755e6b003d90cdb07e61914a.jpg)
[deep learning] the credit card fraud anomaly detection based on the deep learning autoencoder is very effective

拷贝和删除文件

Mobile phone manufacturers "go back to their ancestors", only apple said no

Leetcode 96. Different binary search trees
随机推荐
Leetcode 96. Différents arbres de recherche binaires
Unity typewriter to automatically roll text to the bottom of the text box
Mr developed by unity3d realizes model occlusion and transparent ground receiving shadow
MySQL 服务演进
Automatic mapping of tailored landmark representations for automated driving and map learning
深度神经网络每秒分类近20亿张图像,新型类脑光学分类器芯片登上Nature
Program, calculate 2/1+3/2+5/3+8/5 Value of. It is required to calculate the sum of the first n items and keep 2 decimal places (starting from the second item of the sequence, the numerator of each it
OFFICE技术讲座:标点符号-英文-大全
Ant financial services Yang Jun: evolution of ant data analysis platform and application of data analysis methods
Can qiniu open an account? Is it safe to open an account in qiniu
Yet Another Palindrome Partitioning
蔚来:“拿捏”了数据,“扭捏”着未来
用C语言创建基本的栈与队列
【抬杠C#】如何实现接口的base调用
如何才能把团队给带解散。。。
Shell Encyclopedia
【Spark】(task8)SparkML中的pipeline通道建立
From "chemist" to developer, from Oracle to tdengine, two important choices in my life
【Golang】创建有配置参数的结构体时,可选参数应该怎么传?
VDO-SLAM源码阅读笔记[1] Track()中动态obj部分