当前位置:网站首页>The foreach map in JS cannot jump out of the loop problem and whether foreach will modify the original array
The foreach map in JS cannot jump out of the loop problem and whether foreach will modify the original array
2022-07-08 01:38:00 【Coding Su】
for To jump out of the whole cycle is to use break, But in an array, use forEach Loop or map To exit the whole cycle break Will report a mistake , Use return You can't jump out of the loop ,
One .JavaScript in forEach map Method Unable to jump out of the loop problem and solution
1.forEach map Use break Report errors
let arr = [1, 2, 3, 4, 5];
arr.map((item, index) => {
// forEach Same
if (item === 3) {
break;
}
console.log(item);
});
2.forEach map Use return Do not exit the loop
let arr = [1, 2, 3, 4, 5];
arr.map((item, index) => {
// forEach Same
if (item === 3) {
return;
}
console.log(item);
});
How to solve the problem of jumping out of the loop :
3. Method 1 : Use for loop
const arr1 = [1, 2, 3, 4, 5];
const count = 3;
function test() {
for (let i = 0; i < arr.length; i++) {
if (arr[i] == count) {
return arr[i]
}
}
}
console.log(test()) // 3
4. Method 2 : some () When inside return true Jump out of the whole cycle
const arr2 = [1, 2, 3, 4, 5];
const b = 3;
arr2.some((item) => {
if (item == b) {
return item; // The return value is true, And out of the loop
}
console.log(item);
})
5. Method 3 :every() When inside return false Jump out of the whole cycle ( Need to write return true )
const arr3 = [1, 2, 3, 4, 5];
const c = 3;
arr3.every((item) => {
if (item == c) {
return false;
} else {
console.log(item);
return true;
}
})
Two . About forEach Will it change the original array problem
interviewer :JavaScript Use in forEach Will the original array be changed ?
answer : If the value in the array is a base type , Can't change ; If it is a reference type, there are two cases :1、 The address value of the formal parameter element is not modified , Just modify some attributes inside the formal parameter element , It's going to change the array ;2、 When modifying the entire element object directly , Cannot change the original array ;
2.1、 The elements of the array are basic data types :( Cannot change the original array )
Modify the basic data type String Number Boolean Undefined Null, Then it won't change
let numArr = [1, 2, 3];
numArr.forEach((item) => {
item = item * 2;
});
console.log(numArr); // Print the results :[1, 2, 3] , No [2, 4, 6]
2.2、 The elements of the array are reference data types :( When modifying the entire element object directly , Cannot change the original array )
let objArr = [
{
name: ' Zhang San ', age: 20 },
{
name: ' Li Si ', age: 30 },
];
objArr.forEach((item) => {
item = {
name: ' Wang Wu ',
age: '29',
};
});
console.log(JSON.stringify(objArr));
// Print the results :[{"name": " Zhang San ","age": 20},{"name": " Li Si ","age": 30}]
2.3、 The elements of the array are reference data types :( When modifying an attribute in an element object , You can change the original array ))
let objArr = [
{
name: ' Zhang San ', age: 28 },
{
name: ' Li Si ', age: 30 },
];
objArr.forEach((item) => {
item.name = ' Wang Wu ';
});
console.log(JSON.stringify(objArr));
// Print the results :[{"name":" Wang Wu ","age":28},{"name":" Wang Wu ","age":30}]
2.4. How to change the value of the basic type in the original array :
You can use the second parameter index To change the array
let array = [1, 2, 3, 4];
array.forEach((item,index) => {
array[index] = item * 2
})
console.log(array); // [2, 4, 6, 8]
If you just traverse the array , that , It can be used forEach() Method
however , If you want to traverse the array at the same time , To change the contents of the elements in the array , that , It's best to use it. map() Method to do , Do not use forEach() Method , Avoid some low-level errors .
Reference resources :https://blog.csdn.net/Teemo_shape/article/details/124290093
https://blog.csdn.net/zhangwenok/article/details/124692883
https://blog.csdn.net/Jenn168/article/details/105006701
边栏推荐
- 解决报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
- 能力贡献 GBASE三大解决方案入选“金融信创生态实验室-金融信创解决方案(第一批)”
- About snake equation (5)
- 腾讯游戏客户端开发面试 (Unity + Cocos) 双重轰炸 社招6轮面试
- 云原生应用开发之 gRPC 入门
- 4. Strategic Learning
- ANSI / NEMA- MW- 1000-2020 磁铁线标准。. 最新原版
- 2、TD+Learning
- COMSOL - Construction of micro resistance beam model - final temperature distribution and deformation - establishment of geometric model
- QT--创建QT程序
猜你喜欢
qt--将程序打包--不要安装qt-可以直接运行
5. Discrete control and continuous control
break net
QT -- package the program -- don't install qt- you can run it directly
Macro definition and multiple parameters
Gnuradio operation error: error thread [thread per block [12]: < block OFDM_ cyclic_ prefixer(8)>]: Buffer too small
ArrayList源码深度剖析,从最基本的扩容原理,到魔幻的迭代器和fast-fail机制,你想要的这都有!!!
Working principle of stm32gpio port
Matlab code about cosine similarity
2022 high altitude installation, maintenance and demolition examination materials and high altitude installation, maintenance and demolition operation certificate examination
随机推荐
2022 high voltage electrician examination skills and high voltage electrician reexamination examination
Frrouting BGP protocol learning
QT build with built-in application framework -- Hello World -- use min GW 32bit
On the concept and application of filtering in radar signal processing
2021-03-06 - play with the application of reflection in the framework
About how USRP sets the sampling frequency below the minimum sampling frequency reached by the hardware
跨模态语义关联对齐检索-图像文本匹配(Image-Text Matching)
用户之声 | 对于GBase 8a数据库学习的感悟
写一个纯手写的qt的hello world
Anaconda3 download address Tsinghua University open source software mirror station
Blue Bridge Cup embedded (F103) -1 STM32 clock operation and led operation method
快速熟知XML解析
NPM Internal Split module
2022 low voltage electrician examination content and low voltage electrician simulation examination question bank
生态 | 湖仓一体的优选:GBase 8a MPP + XEOS
碳刷滑环在发电机中的作用
Guojingxin center "APEC education +" Shanghai Jiaotong University Japan Cooperation Center x Fudan philosophy class "Zhe Yi" 2022 New Year greetings
AttributeError: ‘str‘ object has no attribute ‘strftime‘
2、TD+Learning
The examination contents of the third batch of Guangdong Provincial Safety Officer a certificate (main person in charge) in 2021 and the free examination questions of the third batch of Guangdong Prov