当前位置:网站首页>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
边栏推荐
- 2、TD+Learning
- Macro definition and multiple parameters
- 2022 safety officer-c certificate examination summary and safety officer-c certificate reexamination examination
- 2022 safety officer-c certificate examination paper and safety officer-c certificate simulated examination question bank
- Kindle operation: transfer downloaded books and change book cover
- FIR filter of IQ signal after AD phase discrimination
- Measure the voltage with analog input (taking Arduino as an example, the range is about 1KV)
- 4. Strategic Learning
- Generic configuration legend
- 碳刷滑环在发电机中的作用
猜你喜欢
5、離散控制與連續控制
如何让导电滑环信号更好
2021-03-14 - play with generics
Arm bare metal
QT--创建QT程序
Kindle operation: transfer downloaded books and change book cover
Taiwan Xinchuang sss1700 latest Chinese specification | sss1700 latest Chinese specification | sss1700datasheet Chinese explanation
COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况---材料的添加
Common configurations in rectangular coordinate system
2022 operation certificate examination for main principals of hazardous chemical business units and main principals of hazardous chemical business units
随机推荐
Different methods for setting headers of different pages in word (the same for footer and page number)
不算不知道,花呗分期的真实利率居然这么高
General configuration tooltip
如果时间是条河
2022 safety officer-a certificate free examination questions and safety officer-a certificate mock examination
[loss function] entropy / relative entropy / cross entropy
redis的持久化方式-RDB和AOF 两种持久化机制
qt--将程序打包--不要安装qt-可以直接运行
Guojingxin center "APEC investment +": some things about the Internet sector today | observation on stabilizing strategic industrial funds
Guojingxin center "APEC education +" Shanghai Jiaotong University Japan Cooperation Center x Fudan philosophy class "Zhe Yi" 2022 New Year greetings
Transportation, new infrastructure and smart highway
Leetcode exercise - Sword finger offer 36 Binary search tree and bidirectional linked list
Smart agricultural technology framework
How does Matplotlib and PIL image integrate and save multiple pictures into one picture
npm 內部拆分模塊
Taiwan Xinchuang sss1700 latest Chinese specification | sss1700 latest Chinese specification | sss1700datasheet Chinese explanation
The combination of relay and led small night light realizes the control of small night light cycle on and off
Frrouting BGP protocol learning
AttributeError: ‘str‘ object has no attribute ‘strftime‘
regular expression