当前位置:网站首页>Js中forEach map无法跳出循环问题以及forEach会不会修改原数组
Js中forEach map无法跳出循环问题以及forEach会不会修改原数组
2022-07-07 23:42:00 【coding苏】
for循环里要跳出整个循环是使用break,但在数组中用forEach循环或者map如要退出整个循环使用break会报错,使用return也不能跳出循环,
一.JavaScript中 forEach map 方法 无法跳出循环问题及解决方案
1.forEach map 使用break报错
let arr = [1, 2, 3, 4, 5];
arr.map((item, index) => {
// forEach一样的
if (item === 3) {
break;
}
console.log(item);
});
2.forEach map 使用return不退出循环
let arr = [1, 2, 3, 4, 5];
arr.map((item, index) => {
// forEach一样的
if (item === 3) {
return;
}
console.log(item);
});
如何解决跳出循环:
3.方法一:使用 for 循环
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.方法二: some () 当内部 return true 时跳出整个循环
const arr2 = [1, 2, 3, 4, 5];
const b = 3;
arr2.some((item) => {
if (item == b) {
return item; // 返回值为true,并跳出循环
}
console.log(item);
})
5.方法三:every() 当内部 return false 时跳出整个循环(需要写 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;
}
})
二.关于forEach会不会改变原数组问题
面试官:JavaScript中使用forEach会改变原来的数组吗?
答:如果数组中的值是基本类型, 改变不了;如果是引用类型分两种情况:1、没有修改形参元素的地址值, 只是修改形参元素内部的某些属性,会改变原数组;2、直接修改整个元素对象时,无法改变原数组;
2.1、数组的元素是基本数据类型:(无法改变原数组)
修改基础数据类型 String Number Boolean Undefined Null,那就不会改变
let numArr = [1, 2, 3];
numArr.forEach((item) => {
item = item * 2;
});
console.log(numArr); // 打印结果:[1, 2, 3] , 不是 [2, 4, 6]
2.2、数组的元素是引用数据类型:(直接修改整个元素对象时,无法改变原数组)
let objArr = [
{
name: '张三', age: 20 },
{
name: '李四', age: 30 },
];
objArr.forEach((item) => {
item = {
name: '王五',
age: '29',
};
});
console.log(JSON.stringify(objArr));
// 打印结果:[{"name": "张三","age": 20},{"name": "李四","age": 30}]
2.3、数组的元素是引用数据类型:(修改元素对象里的某个属性时,可以改变原数组))
let objArr = [
{
name: '张三', age: 28 },
{
name: '李四', age: 30 },
];
objArr.forEach((item) => {
item.name = '王五';
});
console.log(JSON.stringify(objArr));
// 打印结果:[{"name":"王五","age":28},{"name":"王五","age":30}]
2.4. 如何改变原数组中基本类型的值:
可以借助第二个参数index来改变数组
let array = [1, 2, 3, 4];
array.forEach((item,index) => {
array[index] = item * 2
})
console.log(array); // [2, 4, 6, 8]
如果纯粹只是遍历数组,那么,可以用 forEach() 方法
但是,如果你想在遍历数组的同时,去改变数组里的元素内容,那么,最好是用 map() 方法来做,不要用 forEach()方法,避免出现一些低级错误。
参考: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
边栏推荐
- 4. Strategic Learning
- 2022 safety officer-c certificate examination paper and safety officer-c certificate simulated examination question bank
- Macro definition and multiple parameters
- 2、TD+Learning
- 小金额炒股,在手机上开户安全吗?
- General configuration tooltip
- COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况---材料的添加
- Working principle of stm32gpio port
- 2022 chemical automation control instrument examination summary and chemical automation control instrument simulation examination questions
- 2022 high altitude installation, maintenance and demolition examination materials and high altitude installation, maintenance and demolition operation certificate examination
猜你喜欢
On the concept and application of filtering in radar signal processing
Gnuradio 3.9 using OOT custom module problem record
2022 safety officer-c certificate examination paper and safety officer-c certificate simulated examination question bank
About snake equation (5)
4. Apprentissage stratégique
2021 welder (primary) examination skills and welder (primary) operation examination question bank
2022 safety officer-a certificate free examination questions and safety officer-a certificate mock examination
2022 refrigeration and air conditioning equipment operation examination questions and refrigeration and air conditioning equipment operation examination skills
Matlab code about cosine similarity
Basic implementation of pie chart
随机推荐
A little experience from reading "civilization, modernization, value investment and China"
2021 tea master (primary) examination materials and tea master (primary) simulation test questions
[loss function] entropy / relative entropy / cross entropy
nacos-微服务网关Gateway组件 +Swagger2接口生成
COMSOL - Construction of micro resistance beam model - final temperature distribution and deformation - establishment of geometric model
Taiwan Xinchuang sss1700 latest Chinese specification | sss1700 latest Chinese specification | sss1700datasheet Chinese explanation
Call (import) in Jupiter notebook ipynb . Py file
小金额炒股,在手机上开户安全吗?
4、策略学习
Kindle operation: transfer downloaded books and change book cover
High quality USB sound card / audio chip sss1700 | sss1700 design 96 kHz 24 bit sampling rate USB headset microphone scheme | sss1700 Chinese design scheme explanation
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
STM32GPIO口的工作原理
QT build with built-in application framework -- Hello World -- use min GW 32bit
FIR filter of IQ signal after AD phase discrimination
2022 new examination questions for crane driver (limited to bridge crane) and question bank for crane driver (limited to bridge crane) operation examination
Introduction to the types and repair methods of chip Eco
跨模态语义关联对齐检索-图像文本匹配(Image-Text Matching)
The persistence mode of redis - RDB and AOF persistence mechanisms
NPDP在国内有认可度吗?看一看就明白了!