“This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
1.1 the forEach () method
Definition and usage: the forEach() method calls the function once forEach element in the array, in order.
Note: The forEach() method is not executed for array elements that have no value.
Grammar:
array.forEach(function(currentValue, index, arr), thisValue)
Copy the code
Problem 1: Using return does not exit the loop
const arr = [1.2.3.4.5];
const test = 3;
arr.forEach((item) = > {
if(item == test){
return item
}
console.log(item);
})
Copy the code
Problem 2: An error is reported using break
const arr = [1.2.3.4.5];
const test = 3;
arr.forEach((item) = > {
if(item == test){
break
}
console.log(item);
})
Copy the code
1.2 the map () method
Definition and Usage:
The map() method returns a new array whose elements are the values processed by the call to the original array element.
The map() method processes the elements in their original array order.
Note: Map () does not detect an empty array and does not alter the original array.
Grammar:
array.map(function(currentValue,index,arr), thisValue)
Copy the code
Problem 1: Using return does not exit the loop
const arr = [1.2.3.4.5];
const test = 3;
arr.map((item) = > {
if(item == test){
return
}
console.log(item);
})
Copy the code
Problem 2: An error is reported using break
const arr = [1.2.3.4.5];
const test = 3;
arr.map((item) = > {
if(item == test){
break
}
console.log(item);
})
Copy the code
2. Solutions
2.1 Using the For loop
Note: A return can only appear in the body of a function, that is, in function or {}. Uncaught SyntaxError: Illegal return statement Uncaught SyntaxError: Illegal return statement
const arr = [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())
Copy the code
2.2 Use some () to break out of the loop when an internal return is true
const arr = [1.2.3.4.5];
const test = 3;
arr.some((item) = > {
if(item == test){
return item; // Returns true and breaks out of the loop
}
console.log(item);
})
Copy the code
2.3 Use every() to break out of the loop when internal return false (return true is required)
const arr = [1.2.3.4.5];
const test = 3;
arr.every((item) = > {
if(item == test){
return false;
}else{
console.log(item);
return true; }})Copy the code
Portal: Several methods of iterating over arrays in JavaScript