当前位置:网站首页>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
边栏推荐
- ANSI / NEMA- MW- 1000-2020 磁铁线标准。. 最新原版
- NPDP在国内有认可度吗?看一看就明白了!
- Gnuradio operation error: error thread [thread per block [12]: < block OFDM_ cyclic_ prefixer(8)>]: Buffer too small
- Leetcode exercise - Sword finger offer 36 Binary search tree and bidirectional linked list
- break net
- 4. Apprentissage stratégique
- A little experience from reading "civilization, modernization, value investment and China"
- Application of state mode in JSF source code
- Kafka connect synchronizes Kafka data to MySQL
- qt--將程序打包--不要安裝qt-可以直接運行
猜你喜欢
![[loss function] entropy / relative entropy / cross entropy](/img/bc/574a4745336b0baf1a4ca53af41a82.jpg)
[loss function] entropy / relative entropy / cross entropy

子矩阵的和

QT build with built-in application framework -- Hello World -- use min GW 32bit

Getting started STM32 -- how to learn stm32

Measure the voltage with analog input (taking Arduino as an example, the range is about 1KV)

Probability distribution

Guojingxin center "APEC education +" Shanghai Jiaotong University Japan Cooperation Center x Fudan philosophy class "Zhe Yi" 2022 New Year greetings

Solve the error: NPM warn config global ` --global`, `--local` are deprecated Use `--location=global` instead.

2、TD+Learning

Matlab code about cosine similarity
随机推荐
4、策略学习
QT build with built-in application framework -- Hello World -- use min GW 32bit
Redis cluster
3、多智能体强化学习
Measure the voltage with analog input (taking Arduino as an example, the range is about 1KV)
LaTeX 中 xcolor 颜色的用法
Led serial communication
2021-03-14 - play with generics
About snake equation (1)
2022 high voltage electrician examination skills and high voltage electrician reexamination examination
COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况----几何模型的建立
不算不知道,花呗分期的真实利率居然这么高
5. Discrete control and continuous control
从Starfish OS持续对SFO的通缩消耗,长远看SFO的价值
Android 创建的sqlite3数据存放位置
Anaconda3 tutorial on installing and adding Tsinghua image files
2、TD+Learning
Running OFDM in gnuradio_ RX error: gr:: Log: info: packet_ headerparser_ b0 - Detected an invalid packet at item ××
Grey correlation analysis link (portal) matlab
GBASE观察 | 数据泄露频发 信息系统安全应如何守护