当前位置:网站首页>[interview] Why do you need foreach with the for cycle?
[interview] Why do you need foreach with the for cycle?
2022-07-24 08:04:00 【Small source】
Catalog
for Circulation and forEach The essential difference
for Circulation and forEach The grammatical difference between
forEach Delete own elements ,index Cannot be reset
for The loop can control the start of the loop
for Circulation and forEach The difference in performance
for Circulation and forEach Of Essential difference
for Cycle is js The circular method that existed when it was proposed .forEach yes ES5 Proposed , Methods mounted on iteratable object prototypes , for example Array Set Map.forEach It's an iterator , Responsible for traversing iteratable objects . that Traverse , iteration , Iteratable object What are the differences .
Traverse : It refers to the regular and one-time access to each member of the data structure .
iteration : Iteration is a special form of recursion , Is a method provided by the iterator , By default, it is in a certain order one by one Access data structure members . Iteration is also an ergodic behavior .
Iteratable object :ES6 Introduced in iterable type ,Array Set Map String arguments NodeList All belong to iterable, Their characteristic is that they all have [Symbol.iterator] Method , The object containing it is considered iterative iterable.

After knowing this, you know forEach It's actually an iterator , He and for The essential difference between loops is forEach Is responsible for traversal (Array Set Map) Of iteratable objects , and for A loop is a loop mechanism , It just traverses the array .
Let's talk about what it is iterator , Remember what I mentioned before Generator generator , When it is called, an iterator object is generated (Iterator Object), It has one .next() Method , Each call returns an object {value:value,done:Boolean},value The return is yield The return value after , When yield end ,done Turn into true, Internal values are accessed through successive calls and successive iterations .
iterator It's a special object .ES6 In the specification, its flag is the return object next() Method , Iterative behavior judgment in done In . Without exposing the internal representation , Iterators implement traversal . Look at the code
let arr = [1, 2, 3, 4] // Iteratable object
let iterator = arr[Symbol.iterator]() // call Symbol.iterator After that, the iterator object is generated
console.log(iterator.next()); // {value: 1, done: false} Access to iterator objects next Method
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
We see that . As long as it's an iterable object , Call internal Symbol.iterator Will provide an iterator , And according to the... Returned by the iterator next Method to access the internal , This is also for...of Implementation principle of .
let arr = [1, 2, 3, 4]
for (const item of arr) {
console.log(item); // 1 2 3 4
}
Call next Method returns the value Value and save in item in , until value by undefined Out of the loop , All iteratable objects are available for for...of consumption . Let's look at other iteratable objects :
function num(params) {
console.log(arguments); // Arguments(6) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
let iterator = arguments[Symbol.iterator]()
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
}
num(1, 2, 3, 4)
let set = new Set('1234')
set.forEach(item => {
console.log(item); // 1 2 3 4
})
let iterator = set[Symbol.iterator]()
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
So we can also intuitively see Symbol.iterator Property can generate an iterator when called , and forEach Also generate an iterator , Pass the value of each element in the internal callback function .
( Interested students can search forEach Source code , Array Set Map All instances are mounted with forEach, But most of the answers on the Internet are through length Length of judgement , utilize for The implementation of the loop mechanism . But in Set Map Error will be reported when used on , So I think it's the iterator of the call , Keep calling next, Pass parameter to callback function . Because I can't find the answer on the Internet, I don't make a rash assertion , People with answers can leave a message in the comment area )
for Circulation and forEach The grammatical difference between
Understand the essential difference , In the process of application , What are the grammatical differences between them ?
forEachParameters of .forEachThe interrupt .forEachDelete own elements ,index Cannot be reset .forThe loop can control the start of the loop .
forEach Parameters of
We really know forEach The complete transmission of reference content ? It's probably like this :
arr.forEach((self,index,arr) =>{},this)
self: The elements currently traversed by the array , By default, get array elements from left to right .
index: The index of the current element of the array , The first element index is 0, By analogy .
arr: The current traversal array .
this: In the callback function this Point to .
let arr = [1, 2, 3, 4];
let person = {
name: ' Technical straight stars '
};
arr.forEach(function (self, index, arr) {
console.log(` The current element is ${self} The index for ${index}, Belongs to an array ${arr}`);
console.log(this.name+=' How handsome ');
}, person)
We can use arr Implementation of array de duplication :
let arr1 = [1, 2, 1, 3, 1];
let arr2 = [];
arr1.forEach(function (self, index, arr) {
arr.indexOf(self) === index ? arr2.push(self) : null;
});
console.log(arr2); // [1,2,3]

forEach The interrupt
stay js There is break return continue Interrupt a function or jump out of a loop , We are for Some interrupt behaviors will be used in the loop , It is good for optimizing array traversal lookup , But because of forEach Belongs to iterators , It can only be traversed in order , Therefore, the above interrupt behavior is not supported .
let arr = [1, 2, 3, 4],
i = 0,
length = arr.length;
for (; i < length; i++) {
console.log(arr[i]); //1,2
if (arr[i] === 2) {
break;
};
};
arr.forEach((self,index) => {
console.log(self);
if (self === 2) {
break; // Report errors
};
});
arr.forEach((self,index) => {
console.log(self);
if (self === 2) {
continue; // Report errors
};
});
If I have to be in forEach Jump out of the loop ? There's a way , With the help of try/catch:
try {
var arr = [1, 2, 3, 4];
arr.forEach(function (item, index) {
// Jump out of the condition
if (item === 3) {
throw new Error("LoopTerminates");
}
//do something
console.log(item);
});
} catch (e) {
if (e.message !== "LoopTerminates") throw e;
};
If return No errors are reported , But it won't work
let arr = [1, 2, 3, 4];function find(array, num) { array.forEach((self, index) => { if (self === num) { return index; }; });};let index = find(arr, 2);// undefined
forEach Delete own elements ,index Cannot be reset
stay forEach We can't control index Value , It will only increase mindlessly until it is greater than the... Of the array length Out of the loop . So you can't delete yourself for index Reset , Let's start with a simple example :
let arr = [1,2,3,4]
arr.forEach((item, index) => {
console.log(item); // 1 2 3 4
index++;
});
index It will not change with the increase or decrease of it inside the function body . In actual development , It's very common to traverse an array and delete an item at the same time , In the use of forEach When deleting, pay attention to .
for The loop can control the start of the loop
As mentioned above forEach The starting point of the cycle can only be 0 No human intervention , and for The cycle is different :
let arr = [1, 2, 3, 4],
i = 1,
length = arr.length;
for (; i < length; i++) {
console.log(arr[i]) // 2 3 4
};
The previous array traversal and deletion operation can be written as
let arr = [1, 2, 1],
i = 0,
length = arr.length;
for (; i < length; i++) {
// Delete all... In the array 1
if (arr[i] === 1) {
arr.splice(i, 1);
// Reset i, otherwise i Can jump a
i--;
};
};
console.log(arr); // [2]
// Equivalent to
var arr1 = arr.filter(index => index !== 1);
console.log(arr1) // [2]for Circulation and forEach The difference in performance
In terms of performance comparison, we add map iterator , It is associated with filter The same is to generate a new array . We compared for forEach map What is the performance of in a browser environment :
Performance comparison :for > forEach > map stay chrome 62 and Node.js v9.1.0 In the environment :for Cycle ratio forEach fast 1 times ,forEach Than map fast 20% about .
Cause analysis for:for The loop has no additional function call stack and context , So its implementation is the simplest .forEach: about forEach Come on , Its function signature contains parameters and context , So the performance will be lower than for loop .map:map The slowest reason is because map Will return a new array , The creation and assignment of arrays will result in the allocation of memory space , Therefore, it will bring large performance overhead .
If you will map Nested in a loop , It will bring more unnecessary memory consumption . When you use iterators to traverse an array , If you don't need to return a new array, use map It is against the original intention of the design . When I was working on front-end cooperative development, I saw a lot of people just use it to traverse arrays map Of :
let data = [];
let data2 = [1,2,3];
data2.map(item=>data.push(item));
At the end : This is a problem encountered in the interview , At that time, I only knew the grammatical differences . Not from Iteratable object , iterator , generator and Performance aspect , Further distinguish the similarities and differences between the two from multiple angles , I also hope to elaborate on a simple problem from multiple perspectives , Let's make it clear .
边栏推荐
- Kubernetes: (I) basic concepts
- P3916图的遍历 题解
- Image feature Harris corner detection
- NFT概念究竟是怎么回事。。全面了解NFT市场、技术和案例
- Summary of study notes (I)
- 33 introduction to sparksql, dataframe and dataset
- [golang from introduction to practice] student achievement management system
- Avoid pitfalls and stay away from PUA in the workplace. You need to know the common routines and scripts of PUA!
- jmeter中JSON提取器使用
- 避坑,职场远离PUA,PUA常见的套路与话术你得了解一下!
猜你喜欢

Generative model and discriminant model

*Yolo5 learning * data experiment based on yolo5 face combined with attention model CBAM

Introduction of some functions or methods in DGL Library

What is the NFT concept.. Fully understand NFT market, technology and cases

About the solution of thinking that you download torch as a GPU version, but the result is really a CPU version

EZDML逆向工程导入数据库分析实操教程

Super simple countdown code writing

Detailed notes on pytoch building neural network

Debug No4 use renderdoc to troubleshoot bugs

HCIP第七天
随机推荐
P1305新二叉树题解
学习笔记总结篇(一)
Intelligent robot and intelligent system (Professor Zhengzheng of Dalian University of Technology) -- 5. Bionic robot
生成模型与判别模型
UVA572油田 Oil Deposits题解
hcip第八天笔记
SIFT feature point extraction
What is NFT? An article to understand the concept of NFT
Collection of binary tree topics
避坑,职场远离PUA,PUA常见的套路与话术你得了解一下!
Solution of p3916 graph traversal problem
Movie recommendation system
abstract class
*Yolo5 learning * data experiment based on yolo5 face combined with attention model se
Saining Techtalk attack and defense drill: attack combination fist "stable, accurate and ruthless" penetration
Learning dynamic Siamese network for visual object tracking full text translation
Jetson AgX Orin source change
多种优化方法打印100~200之间的素数
Avoid pitfalls and stay away from PUA in the workplace. You need to know the common routines and scripts of PUA!
rbm 对比散度