Take a few minutes to relive the basics of the JavaScript loop guide and remember a figure
During front-end development, we often use JavaScript to provide a lot of loop and iteration methods, common
for, for... of,for... in,while, Array.forEach, as well as Array.* (There are also some Array methods similar to loop/iterator: Array.values (), Array.keys (), Array.map () , Array.reducer (), etc.), and these are very basic things, there must be people who think these are very basic. Something, what's good looking at? The purpose of these things is to be framed and brainized. So it's simple to make a diagram of a JS loop. Integrate cluttered, fragmented knowledge into everything, making it easier to remember thebasics.
Simple Loop
for
The for loop repeats as long as certain conditions are met. It is usually used to execute a code block a certain number of times.
array loop
const arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) {
console.log(arr[i])
}
break statement
Use break statement to terminate a loop
for ( let i = 0 ;; i++) {
console.log ( ' loop ')
break
}
// output: loop
In this case, in the for loop, the break keyword exits the loop when it encounters the loop.
continue statement
The continue statement can be used to continue execution (skip the rest of the code block and go to the next loop)
for ( let i = 0 ; i < 3; i++) {
if (i === 2) continue
console.log (i)
}
// output: 0, 1
The above code can enter the result, when condition
i === 2 is established, encounter continue keyword to skip and proceed to the next loop. for…of
The for... of statement creates a loop on an iterable object (including Array, Map, Set, arguments, and so on), with each unique property of the value with one iteration.
string string loop
let string = 'text'
for (let value of string) {
console.log(value) // output "t", "e", "x", "t"
}
array array loop
let arr = [0, 1, 2]
for (let value of arr) {
console.log(value) // output 0, 1, 2
}
objects object loop
For... of loop works only for iterable values, objects are not iterable, so it is not feasible to loop objects directly using for... of. The following example:
let object = { a: 1, b: 2, c: 3 }
for (let value of object) // Error: object is not iterable
console.log(value)
You can convert an object to an iterable object using the built-in Object method:
.keys (),.values () or.entries (), see the following example:let enumerable = { property : 1, method : () => {} };
for (let key of Object.keys( enumerable )) console.log(key);
> property
> method
for (let value of Object.values( enumerable )) console.log(value);
> 1
> () => {}
for (let entry of Object.entries( enumerable )) console.log(entry);
> (2) ["prop", 1]
> (2) ["meth", ƒ()]
It can also be achieved by using a for... in loop without using the built-in Object method.
for…in
A for... in loop is a special type of loop that traverses the properties of an object or the elements of an array. When traversing objects, you can display enumerable object properties
let object = { a: 1, b: 2, c: 3, method: () => {} }
for (let value in object) {
console.log(value, object[value])
}
// output: 1, 2, 3, () => { }
while
A while statement executes its block as long as the specified condition evaluates to true (true).
let c = 0
while (c++ < 5) {
console.log (c)
}
// output: 1, 2, 3, 4, 5
do... while
is very similar to while, while the do... while statement repeats until the specified condition evaluates to a false value (false).
var i = 1
do {
console.log (i)
i++
} while (i <= 5)
// output: 1, 2, 3, 4, 5
Arrays Loops
Array has several iteration methods. Usually we recommend using the built-in Array method for loop operations instead of using for or while loops. The array method is attached to the Array.prototype property, which means that it is used directly from the array object.
For example, using
Array.forEach ()method to manipulate an array
forEach
Definition: The forEach method executs the given function once on each element of the array.
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
every
Definition: checks whether all elements of the array meet the judgment criteria, returns true, otherwise false
Return value: boolean
const isBelowThreshold = (currentValue = currentValue < 40)
const array1 = [1, 30, 39, 29, 10, 13]
console.log(array1.every(isBelowThreshold))
// output: true
some
Definition: whether there are elements in the array that satisfy the judgment criteria.
If at least one of the judgment conditions is satisfied, the return value isfalse ifnone are satisfied:boolean
filter
Definition: Execres the given function once on each element of the array, returning a new array
Return value: 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"]
map
Definition: The method creates a new array whose result is the return value after each element of the array has been called once.
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]
reduce && reduceRight
Definition: The
reducemethod performs a reducer function (in ascending order) supplied by you on each element of the array, summarising its results as 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
Definition:
reduceRightmethod accepts a function as accumulator and each value of an array (right to left) ) to reduce it 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]
find()& findIndex()
Definition: The
find method is used to find the first array member that matches the condition, and returns the member if there are no members that match the condition undefined. const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
Definition:
findIndexreturns the position of the first array member that matches the condition, or -1 if all members do not match the condition. const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3


No comments:
Post a Comment