当前位置:网站首页>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);
     });

 Insert picture description here

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);
  });

 Insert picture description here
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

 Insert picture description here

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);
 })

 Insert picture description here

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;
     }
 })

 Insert picture description here

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

原网站

版权声明
本文为[Coding Su]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207072340157441.html