当前位置:网站首页>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
边栏推荐
- Cs5261type-c to HDMI alternative ag9310 | ag9310 alternative
- Write a pure handwritten QT Hello World
- Transportation, new infrastructure and smart highway
- Kuntai ch7511b scheme design | ch7511b design EDP to LVDS data | pin to pin replaces ch7511b circuit design
- How does Matplotlib and PIL image integrate and save multiple pictures into one picture
- qt-使用自带的应用框架建立--hello world--使用min GW 32bit
- The persistence mode of redis - RDB and AOF persistence mechanisms
- Guojingxin center "APEC investment +": some things about the Internet sector today | observation on stabilizing strategic industrial funds
- Redis 主从复制
- Mat file usage
猜你喜欢

Basic realization of line chart (II)

Getting started STM32 -- how to learn stm32

Redis cluster

3. Multi agent reinforcement learning

nacos-微服务网关Gateway组件 +Swagger2接口生成

Gnuradio 3.9 using OOT custom module problem record

qt--将程序打包--不要安装qt-可以直接运行

The persistence mode of redis - RDB and AOF persistence mechanisms

Common configurations in rectangular coordinate system

COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况----几何模型的建立
随机推荐
About snake equation (2)
2022 new examination questions for crane driver (limited to bridge crane) and question bank for crane driver (limited to bridge crane) operation examination
qt--將程序打包--不要安裝qt-可以直接運行
正则表达式
Guojingxin center "APEC education +" Shanghai Jiaotong University Japan Cooperation Center x Fudan philosophy class "Zhe Yi" 2022 New Year greetings
Introduction to natural language processing (NLP) based on transformers
Ag9310 same function alternative | cs5261 replaces ag9310type-c to HDMI single switch screen alternative | low BOM replaces ag9310 design
Parade ps8625 | replace ps8625 | EDP to LVDS screen adapter or screen drive board
Kafka connect synchronizes Kafka data to MySQL
LaTeX 中 xcolor 颜色的用法
LeetCode 练习——剑指 Offer 36. 二叉搜索树与双向链表
STM32GPIO口的工作原理
Use "recombined netlist" to automatically activate eco "APR netlist"
Kaptcha generates verification code on Web page
2022 safety officer-c certificate examination summary and safety officer-c certificate reexamination examination
NPM internal split module
Grey correlation analysis link (portal) matlab
About snake equation (5)
Usage of xcolor color in latex
5、離散控制與連續控制