当前位置:网站首页>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
边栏推荐
- Guojingxin center "friendship and righteousness" - the meta universe based on friendship and friendship, and the parallel of "honguniverse"
- Tapdata 的 2.0 版 ,開源的 Live Data Platform 現已發布
- How does Matplotlib generate multiple pictures in turn & only save these pictures without displaying them in the compiler
- 滑环使用如何固定
- 如果时间是条河
- common commands
- 写一个纯手写的qt的hello world
- Gnuradio operation error: error thread [thread per block [12]: < block OFDM_ cyclic_ prefixer(8)>]: Buffer too small
- Understanding of maximum likelihood estimation
- After modifying the background of jupyter notebook and adding jupyterthemes, enter 'JT -l' and the error 'JT' is not an internal or external command, nor a runnable program
猜你喜欢

解决报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.

The combination of relay and led small night light realizes the control of small night light cycle on and off

Working principle of stm32gpio port

ArrayList源码深度剖析,从最基本的扩容原理,到魔幻的迭代器和fast-fail机制,你想要的这都有!!!

Gnuradio transmits video and displays it in real time using VLC

Understanding of prior probability, posterior probability and Bayesian formula

About snake equation (1)

2、TD+Learning

Running OFDM in gnuradio_ RX error: gr:: Log: info: packet_ headerparser_ b0 - Detected an invalid packet at item ××

The persistence mode of redis - RDB and AOF persistence mechanisms
随机推荐
Leetcode exercise - Sword finger offer 36 Binary search tree and bidirectional linked list
3、多智能体强化学习
Gnuradio 3.9 using OOT custom module problem record
2022 operation certificate examination for main principals of hazardous chemical business units and main principals of hazardous chemical business units
How does Matplotlib generate multiple pictures in turn & only save these pictures without displaying them in the compiler
The usage of rand function in MATLAB
Working principle of stm32gpio port
2021-03-14 - play with generics
从Starfish OS持续对SFO的通缩消耗,长远看SFO的价值
Getting started STM32 -- how to learn stm32
GBASE观察 | 数据泄露频发 信息系统安全应如何守护
跨模态语义关联对齐检索-图像文本匹配(Image-Text Matching)
COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况----几何模型的建立
Matlab method is good~
Introduction to natural language processing (NLP) based on transformers
Qt - - Packaging Programs - - Don't install Qt - can run directly
2021-04-12 - new features lambda expression and function functional interface programming
The beauty of Mathematics -- the principle of fine Fourier transform
redis的持久化方式-RDB和AOF 两种持久化机制
About snake equation (1)