当前位置:网站首页>Summary of different circulation modes and precautions in JS
Summary of different circulation modes and precautions in JS
2022-07-23 14:17:00 【Please code】
List of articles
Write it at the front
This article is mainly about js Make a summary in the way of circulation , Including common circulation methods and matters needing attention , I try to write as clearly as possible , Because many too small details may not be fully understood by myself !
Circulation is a common way
- for
- while
- for in
- for of
- forEach
Basic data preparation
// Declare a dense array , If not fill If it's filled , The default is a sparse array
let arr = new Array(9999999).fill(9) // For testing performance
let tR = [2, 3, 4, 5, 3, 2, 1] // For testing characteristics
let i = 0 //for Recycling
let obj = {
name: 'jim',
[Symbol('sm')]: 800,
get: function () {
},
childObj: {
},
num: 900,
1: 888,
} //for of and for in Test features using
Performance comparison
// Test common for loop
console.time('for')
for (let i = 0; i < arr.length; i++) {
}
console.timeEnd('for')
//for: 6.968017578125 ms
// test while loop
console.time('while')
while (i < arr.length) {
i++
}
console.timeEnd('while')
//while: 34.88720703125 ms
// test for in
console.time('for in')
for (let i in arr) {
}
console.timeEnd('for in')
//for in: 2076.422119140625 ms
// test for of
console.time('for of')
for (let i of arr) {
}
console.timeEnd('for of')
//for of: 129.52490234375 ms
// test foreach
console.time('for each')
arr.forEach(() => {
})
console.timeEnd('for each')
//for each: 88.530029296875 ms
characteristic
for loop
/** == for loop + It's more customizable Anytime break and continue To decide whether to continue the cycle + Judgment conditions can be modified at will + You can modify each value during the cycle You can also change the data of the source array - It's troublesome , You need to use an array [ Subscript ] To operate the value */
new Promise(res => {
for (; i < tR.length; i++) {
if (i % 2 == 0) {
tR[i] = 'new'
}
}
res()
}).then(() => {
console.log(tR) //['new', 3, 'new', 5, 'new', 2, 'new']
})
while loop
/** == while loop + The loop can be terminated by judging the condition + Judgment conditions can be modified at will + The value can be unchanged during the cycle , The source array will not be changed - It is generally applicable to the premise that the number of cycles is not known , Use a condition to terminate the loop Efficiency and for almost , Just don't know the number of cycles can be used while */
new Promise(res => {
while (i > tR.length) {
i++
// delete(tR[i])
if (i % 2 == 0) {
tR[i] = 'new'
}
}
res()
}).then(() => {
console.log(tR) //[2, 3, 4, 5, 3, 2, 1]
})
forEach
/** == forEach loop + Grammar is simple - When traversing, you cannot modify or delete the set data - Method cannot be used break,continue Statement out of loop , Or use return Returns... From the body of the function , Callback functions are not executed for empty arrays */
new Promise(res => {
tR.forEach((v, i, a) => {
//i Will not be changed
i = i + Number(v)
if (i % 2 == 0) {
return
}
if (v == 2) {
// You can execute business logic in the judgment condition , But the data can't be transmitted
console.log(v) // 2
console.log(a) //[2, 3, 4, 5, 3, 2, 1]
}
// Will not be terminated , The source array will not be changed
})
res()
}).then(() => {
console.log(i) //0
})
// The source array will not be changed
new Promise(res => {
tR.forEach((v, i, a) => {
delete (v % 2 == 0)
})
res()
}).then((a) => {
console.log(tR) //[2, 3, 4, 5, 3, 2, 1]
})
for in
/** == for in loop + Grammar is simple + Can be used to traverse objects - When traversing, you cannot modify or delete the set data - Method cannot be used break,continue Statement out of loop , Or use return Returns... From the body of the function , Callback functions are not executed for empty arrays */
// You can change the source array Delete array
let pro = new Promise((res => {
for (let v in tR) {
delete (tR[v])
}
res()
}))
p.then(r => {
console.log(tR) // Sparse array [length = 7]
})
// Traversal array
new Promise(res => {
for (let v in tR) {
i = i + tR[v]
}
res()
}).then(() => {
console.log(i) //20
})
// Points to pay attention to when traversing objects
Object.prototype.fn = function fn() {
} // Public attribute function
Object.prototype.O = 'obj' // Public attribute string
// Numbers ->string->function-> object ->number But I can't traverse Symbol attribute At the same time, the public attributes will be traversed
for (let k in obj) {
console.log(obj[k])
/** ceshi.html:158 888 ceshi.html:158 jim ceshi.html:158 ƒ () { } ceshi.html:158 {} ceshi.html:158 900 ceshi.html:158 ƒ fn() { } ceshi.html:158 obj */
}
for (let k in obj) {
// The non private attribute To filter out
if (obj.hasOwnProperty(k)) {
console.table(obj[k])
}
/** ceshi.html:169 888 ceshi.html:169 jim ceshi.html:169 function () { } ceshi.html:169 ceshi.html:169 900 */
}
// obtain symbol attribute
console.log(Object.getOwnPropertySymbols(obj)) //[Symbol(sm)]
for of
/** == for of loop + Grammar is simple - When traversing, you cannot modify or delete the set data - Method cannot be used break,continue Statement out of loop , Or use return Returns... From the body of the function , Callback functions are not executed for empty arrays The principle is Check whether there is symbol.iterator iterator That is, we can change Symbol The rules of The result output of the change traversal The code is as follows */
// Delete array Do not change the source array
new Promise(res => {
for (let v of tR) {
delete (v % 2 == 0)
}
res()
}).then(() => {
console.log(tR) //[2, 3, 4, 5, 3, 2, 1]
})
// Traversal array
new Promise(res => {
for (let v of tR) {
i = i + v
}
res()
}).then(() => {
console.log(i) //20
})
// Use for of Traversal class array Add... To the object iterator Properties of
let O = {
0: 1,
1: 2,
2: 3,
length: 3 // Don't add lenth Attribute words , Not an array of classes
}
O[Symbol.iterator] = Array.prototype[Symbol.iterator]
for (let v of O) {
console.log(v) //1、2、3
}
// rewrite iterator The way since for of It's based on iterator From the rules , Then we can rewrite his rules to meet our business needs
tR[Symbol.iterator] = () => {
let i = 0
return {
// every last iterator You have to have one next function , The number of times he performs is based on done To determine the ,true It will not be implemented , Otherwise it just keeps going
next() {
// i++
// Here we change the number of iterations
i += 2
if (i > tR.length - 1) {
return {
done: true,
value: null
}
} else {
return {
done: false,
value: tR[i]
}
}
}
}
}
for (let k of tR) {
console.log(k) // 4、3、1
}
summary
This article is not water , In fact, I recently want to js Some basic knowledge in... Is also summarized , In this way, my knowledge system , Also review some details missed before , One purpose of doing this is to consolidate your foundation , Not to waste time on some very simple problems , For example, when we write code , Use for in Traverse the object , Suddenly I found that it was more inexplicable , At this time, you should check whether other colleagues have written some Object Public attribute of , I didn't filter it myself , And so on , So maybe every point of these summaries is not difficult , But the system is not easy , Or down-to-earth slowly ponder ! Thank you
边栏推荐
- Uiscrollview (uicollectionview) prohibits horizontal and vertical sliding at the same time
- 494. 目标和
- STM32输出正弦波+cubeMX配置+HAL库
- Notes on the fourth day
- Tensor、Numpy、PIL格式转换以及图像显示
- C语言实现memcpy、memmove
- 【百企行】牛耳教育助力高校访企拓岗促就业专项行动
- What is Tianji 920 equivalent to a snapdragon? How much is Tianji 920 equivalent to a snapdragon? How about Tianji 920
- Pbootcms数据库转换教程(sqlite转mysql详细教程)
- LabVIEW运行中改变Chart的历史长度
猜你喜欢
随机推荐
强化学习——策略梯度理解点
酷睿i7 1165g7相当于什么水平 i71165g7属于哪个档次
Swift 16进制字符串与UIColor互转
达人评测酷睿i7 12850hx和i7 12700h选哪个
Canvas eraser function
The difference between rtx3080ti and 3090. Which one is more cost-effective, rtx3080ti or 3090
多重背包!
第十一天笔记
Stream stream is used for classification display.
第五天筆記
Le shell a besoin de connaître les commandes
iQOO 10 Pro和vivo X80 Pro区别 哪个好详细参数配置对比
Is machine learning difficult to get started? Tell me how I started machine learning quickly!
494. 目标和
MySQL enables scheduled task execution
第十二天笔记
LabVIEW运行中改变Chart的历史长度
链下数据互操作
接口interface
JS中不同的循环方式和注意事项总结








