Image by Max Duzij

Take a few minutes to go over the basics of the JavaScript loop guide and memorize a diagram

In the front-end development process, we often use JavaScript to provide a variety of loop and iteration methods, common for, for… Of, for… In, while, array. forEach, and Array.* (There are also Array methods that resemble loops/iterators: Array.values(), array.keys (), array.map (), array.reducer (), etc.) These things are sorted out in order to have a framework, a brain map. So it’s easy to make a brain map of JS circulation. Integrating messy, fragmented knowledge into everything makes it easier to remember the basics.

Simple Loop

for

The for loop repeats as long as certain conditions are met. It is usually used to execute a block of code a certain number of times.

An array of circulation

const arr = [1.2.3]
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i])
}
Copy the code

Break statement

Use the break statement to terminate the loop

for (let i = 0; ; i++) {
  console.log('loop')
  break
}

// output: loop
Copy the code

In this case, in the for loop, the break keyword exits the loop when it encounters it.

The continue statement

The continue statement can be used to continue execution (skip the rest of the code block and enter the next loop)

for (let i = 0; i < 3; i++) {
  if (i === 2) continue
  console.log(i)
}

// output: 0, 1
Copy the code

The above code can be entered as a result of skipping the continue keyword and proceeding to the next loop if the condition I === 2 is true.

The for… of

for… The OF statement creates a loop over iterable objects (Array, Map, Set, arguments, and so on) that calls an iteration for each unique attribute of the value.

String string loop

let string = 'text'

for (let value of string) {
  console.log(value) // output "t", "e", "x", "t"
}
Copy the code

Array loop

let arr = [0.1.2]
for (let value of arr) {
  console.log(value) // output 0, 1, 2
}
Copy the code

Object object loop

The for… The of loop only works for iterable values, objects are not iterable, so use for… It is not feasible to loop objects with of. Here are some examples:

let object = { a: 1.b: 2.c: 3 }

for (let value of object) // Error: object is not iterable
  console.log(value)
Copy the code

You can use the built-in Object methods to convert objects to iterables:.keys(),.values(), or.entries(), for example:

let enumerable = { property : 1.method : (a)= >{}};for (let key of Object.keys( enumerable )) console.log(key);
> property
> method

for (let value of Object.values( enumerable )) console.log(value);
> 1
> (a)= > {}

for (let entry of Object.entries( enumerable )) console.log(entry);
> (2) ["prop".1> (2) ["meth", ƒ ()]Copy the code

You can also use for… The in loop is implemented without using the built-in Object method.

The for… in

The for… An IN loop is a special type of loop that iterates over the properties of an object or the elements of an array. Enumerable object properties are displayed as the object is traversed

let object = { a: 1.b: 2.c: 3.method: (a)= >{}}for (let value in object) {
  console.log(value, object[value])
}

// output: 1, 2, 3, () => { }
Copy the code

while

A while statement executes its block as long as the specified condition evaluates to true.

let c = 0

while (c++ < 5) {
  console.log(c} / /output: 1.2.3.4.5
Copy the code

The do… while

Very similar to while, while do… The while statement repeats until the specified condition evaluates to false (false).

var i = 1
do {
  console.log(i)
  i++
} while (i <= 5)

// output: 1, 2, 3, 4, 5
Copy the code

Arrays Loops

Array has multiple iterations. It is generally recommended to use the built-in Array method for loops rather than for or while loops. Array methods are attached to the array. prototype property, which means they are used directly from Array objects. For example, use array.foreach () to manipulate arrays

forEach

Definition: The forEach method performs a given function on each element of the array once. Return value: None

let arr = ['jack'.'tom'.'vincent']

arr.forEach((name) = > console.log(`My name is ${name}`))

//output
// My name is jack
// My name is tom
// My name is vincent
Copy the code

every

Definition: Checks whether all elements of an array meet the criteria, returns true if all elements meet the criteria, otherwise false: Boolean

const isBelowThreshold = (currentValue = currentValue < 40)
const array1 = [1.30.39.29.10.13]

console.log(array1.every(isBelowThreshold))

// output: true
Copy the code

some

Definition: Whether there are elements in the array that meet the criteria. Returns true if at least one of the criteria is met, false if none: Boolean

filter

Definition: Executes a given function on each element of an array once, returning a new array

const words = ['spray'.'limit'.'elite'.'exuberant'.'destruction'.'present'];
const result = words.filter(word= > word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Copy the code

map

Definition: method creates a new array, resulting in the return value of each element in the array after a call to the supplied function. Return value: new array

const array1 = [1.4.9.16];
// pass a function to map
const map1 = array1.map(x= > x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
Copy the code

reduce && reduceRight

Definition: The reduce method performs a Reducer function (in ascending order) that you provide on each element in the array and summarizes its results into a single return value.

const array1 = [1.2.3.4];
const reducer = (accumulator, currentValue) = > accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Copy the code

Definition: The reduceRight method takes a function as an accumulator and reduces each value of the array (from right to left) to a single value.

const array1 = [[0.1], [2.3], [4.5]].reduceRight(
  (accumulator, currentValue) = > accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]
Copy the code

find()& findIndex()

Definition: The find method is used to find the first qualified array member and return that member, or undefined if none exists.

const array1 = [5.12.8.130.44];
const found = array1.find(element= > element > 10);

console.log(found);
// expected output: 12
Copy the code

Definition: findIndex returns the location of the first qualified array member, or -1 if all members fail.

const array1 = [5.12.8.130.44];
const isLargeNumber = (element) = > element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3
Copy the code

reference

  • The Complete Guide to Loops in JavaScript
  • Loops and Iteration (Take a few minutes to refresh)
  • Array (Take a few minutes to review)