Today we’ll take a look at the basics and look at some of the looping methods in JavaScript:

Array traversal method

1. forEach()

The forEach method is used to call each element of the array and pass the element to the callback function. Each value in the array calls the callback function. The syntax is as follows:

array.forEach(function(currentValue, index, arr), thisValue)
Copy the code

The first argument to this method, the callback function, is mandatory and takes three arguments:

  • CurrentValue: Required. The current element
  • Index: Optional. The index value of the current element.
  • Arr: Optional. The array object to which the current element belongs
let arr = [1.2.3.4.5]
arr.forEach((item, index, arr) = > {
  console.log(index+":"+item)
})
Copy the code

The method can also take a second argument that binds the this variable inside the callback function (provided that the callback cannot be an arrow function, since arrow functions do not have this) :

let arr = [1.2.3.4.5]
let arr1 = [9.8.7.6.5]
arr.forEach(function(item, index, arr){
  console.log(this[index])  // 5
}, arr1)
Copy the code

Note:

  • The forEach method does not change the array and does not return a value;
  • ForEach cannot break out of a loop with a break or a continue. A return has the same effect as a continue in a for loop.
  • The forEach method does not iterate over objects, only arrays.

2. map()

The map() method returns a new array with the values of the original array elements processed by the call. This method processes the elements in order of the original array elements. The syntax is as follows:

array.map(function(currentValue,index,arr), thisValue)
Copy the code

The first argument to this method, the callback function, is mandatory and takes three arguments:

  • CurrentValue: Mandatory. The value of the current element;
  • Index: Optional. The index of the current element;
  • Arr: Optional. The array object to which the current element belongs.
let arr = [1.2.3];
 
arr.map(item= > {
    return item + 1;
})

// Output: [2, 3, 4]
Copy the code

The second argument to the method binds the this variable inside the argument function, which is optional:

let arr = ['a'.'b'.'c'];
 
[1.2].map(function (e) {
    return this[e];
}, arr)

['b', 'c']
Copy the code

The method can also be chain-called:

let arr = [1.2.3];
 
arr.map(item= > item + 1).map(item= > item + 1)

// Output result: [3, 4, 5]
Copy the code

Note:

  • The map method does not detect empty arrays;
  • The map method returns a new array when iterating through an array, without changing the original array.
  • The map method has a return value and can return it. The map callback supports the return value.
  • The map method does not iterate over objects, only arrays.

3. for of

for… The of statement creates a loop to iterate over an iterable object. For… introduced in ES6. Of cycle instead of for… In and forEach(), and support the new iteration protocol. The syntax is as follows:

for (variable of iterable) {
    statement
}
Copy the code

This method takes two parameters:

  • Variable: The attribute value of each iteration is assigned to the variable.
  • Iterable: An object with enumerable properties that can be iterated over.

This method allows you to get the key value of an object:

let arr = [
    {id:1.value:'hello'},
    {id:2.value:'world'},
    {id:3.value:'JavaScript'}]for (let item in arr) {
  console.log(item); 
}
// The output is 0, 1, 2
Copy the code

Note:

  • The for of method only iterates through the properties of the current object, not the properties on its prototype chain;
  • The for of method is suitable for iterating over collections of objects such as arrays/arrays/strings/maps/sets;
  • The for of method does not support traversing ordinary objects because it has no iterator objects. If you want to iterate over an object’s properties, use the for in method;
  • You can use break, continue, and return to break the loop loop;

4. filter()

The filter() method is used to filter an array, and the elements that meet the criteria are returned. Its argument is a callback function that executes each element in turn, returning the element true, or an empty array if there are none. The syntax is as follows:

array.filter(function(currentValue,index,arr), thisValue)
Copy the code

The first argument to this method, the callback function, is mandatory and takes three arguments:

  • CurrentValue: Mandatory. The value of the current element;
  • Index: Optional. The index of the current element;
  • Arr: Optional. The array object to which the current element belongs.
const arr = [1.2.3.4.5]
arr.filter(item= > item > 2) 

// Output result: [3, 4, 5]
Copy the code

Again, it takes a second argument that binds the this variable inside the argument function.

We can use the filter() method to remove undefined, null, NAN values from the array:

let arr = [1.undefined.2.null.3.false.' '.4.0]
arr.filter(Boolean)

[1, 2, 3, 4]
Copy the code

Note:

  • The filter method returns a new array and does not alter the original array.
  • The filter method does not detect an empty array;
  • The filter method is only useful for detecting arrays.

5. Some (), every ()

The some() method iterates through each item in the array, returning true as long as there is one element that meets the criteria, and not checking the remaining elements, otherwise returning false.

The every() method iterates over every element in the array, returning true only if all elements are true. If one element in the array is detected as unqualified, the entire expression returns false, and the remaining elements are not checked. The syntax is as follows:

The syntax for both is as follows:

array.some(function(currentValue,index,arr),thisValue)
array.every(function(currentValue,index,arr), thisValue)
Copy the code

The first argument to both methods is a mandatory callback function, which takes three arguments:

  • CurrentValue: Mandatory. The value of the current element;
  • Index: Optional. The index of the current element;
  • Arr: Optional. The array object to which the current element belongs.
let arr = [1.2.3.4.5]
arr.some(item= > item > 4) 

// Output result: true

let arr = [1.2.3.4.5]
arr.every(item= > item > 0) 

// Output result: true
Copy the code

Note:

  • Neither method changes the array and returns a Boolean;
  • Neither method checks for an empty array;
  • Both methods are only suitable for detecting arrays.

6. The reduce (), reduceRight ()

The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value. Reduce () can be used as a higher-order function for compose of functions. The syntax is as follows:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code

The reduce method executes a callback for each element in the array, excluding elements that were deleted or never assigned. The callback takes four arguments:

  • Total: the value returned by the last call to the callback, or the initialValue provided.
  • CurrentValue: The element currently being processed;
  • CurrentIndex: index of the current element;
  • Arr: The array object to which the current element belongs.

The second argument to the method is initialValue, which represents the initialValue passed to the function (as the first argument to the first callback call) :

let arr = [1.2.3.4]
let sum = arr.reduce((prev, cur, index, arr) = > {
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr, sum);
Copy the code

Output result:

1 2 1
3 3 2
6 4 3
[1.2.3.4] 10
Copy the code

Try adding another initial value:

let arr = [1.2.3.4]
let sum = arr.reduce((prev, cur, index, arr) = > {
    console.log(prev, cur, index);
    return prev + cur;
}, 5)
console.log(arr, sum);
Copy the code

Output result:

5 1 0
6 2 1
8 3 2
11 4 3
[1.2.3.4] 15
Copy the code

It follows that if no initialValue is provided, reduce executes the callback method starting at index 1, skipping the first index. If an initialValue initialValue is provided, it is executed from index 0

ReduceRight () method is almost the same as reduce(), except that this method traverses the array in reverse order, while reduce() method traverses in positive order.

let arr = [1.2.3.4]
let sum = arr.reduceRight((prev, cur, index, arr) = > {
    console.log(prev, cur, index);
    return prev + cur;
}, 5)
console.log(arr, sum);
Copy the code

Output result:

5 4 3
9 3 2
12 2 1
14 1 0
[1.2.3.4] 15
Copy the code

Note:

  • Neither method changes the array;
  • Both methods, if they add an initial value, change the original array, putting the initial value at the end of the array;
  • Both methods do not perform callbacks on empty arrays.

7. The find (), findIndex ()

The find() method returns the value of the first element of the array judged by the function. When an element in an array returns true on a test condition, find() returns the element that matches the condition, and the subsequent value is not called. Returns undefined if there are no eligible elements.

The findIndex() method returns the position (index) of the first element in the array passed to the test function. When an element in an array returns true on a function condition, findIndex() returns the index position of the element that meets the condition, and the subsequent value is not called. Returns -1 if no element matches the criteria.

The syntax for both methods is as follows:

array.find(function(currentValue, index, arr),thisValue)
array.findIndex(function(currentValue, index, arr), thisValue)
Copy the code

The first argument to both methods is a mandatory callback function, which takes three arguments:

  • CurrentValue: Required. Current element;
  • Index: Optional. Index of the current element;
  • Arr: Optional. The array object to which the current element belongs.
let arr = [1.2.3.4.5]
arr.find(item= > item > 2) 

// Output: 3

let arr = [1.2.3.4.5]
arr.findIndex(item= > item > 2) 

// Output: 2
Copy the code

The find() and findIndex() methods are almost the same except that they return different results:

  • find(): returns the first value that matches the condition;
  • findIndex: returns the index of the value of the first return condition.

Note:

  • For an empty array, the function does not execute;
  • Both methods do not change the original array.

8. Keys (), values(), entries()

All three methods return an array of iterated objects with different contents:

  • Keys () returns the index of the array;
  • Values () returns the element of the array;
  • Entries () returns an array of key-value pairs.

The syntax for the three methods is as follows:

array.keys()
array.values()
array.entries()
Copy the code

None of these three methods takes parameters:

let arr = ["Banana"."Orange"."Apple"."Mango"];
const iterator1 = arr.keys();
const iterator2 = arr.values() 
const iterator3 = arr.entries() 

for (let item of iterator1) {
  console.log(item);
}
// Output: 0, 1, 2, 3

for (let item of iterator2) {
  console.log(item);
}
// Banana Orange Apple Mango

for (let item of iterator3) {
  console.log(item);
}
/ / output: [0, 'Banana'] [1, 'Orange'] [2, 'Apple'] [3, 'Mango]
Copy the code

Conclusion:

methods Whether to change the original array The characteristics of
forEach() no No return value
map() no It has a return value and can be called chained
for of no for… Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator
filter() no Filter array, returns an array containing the elements that meet the criteria, chainable call
Every (), some () no Some () returns true as long as one of them is true; Every () returns false as long as one of them is false.
The find (), findIndex () no Find () returns the first qualified value; FindIndex () returns the index of the value of the first return condition
Reduce () and reduceRight () no Reduce () operates on arrays in positive order; ReduceRight () inverts the array
Keys (), values(), entries() no Keys () returns the index of the array; Values () returns an array element; Entries () returns an array of key-value pairs.

Object traversal method

1. for in

The for… In is primarily used to loop object properties. Each time the code in the loop executes, it performs an operation on the properties of the object. The syntax is as follows:

for (var inObject) {code block executed}Copy the code

There are two parameters:

  • Var: Mandatory. The specified variable can be an array element or an object property.
  • Object: Mandatory. Specifies the object of the iteration.
var obj = {a: 1.b: 2.c: 3}; 
 
for (var i in obj) { 
    console.log('key name:', i); 
    console.log('Key:', obj[i]); 
}
Copy the code

Output result:

Key: A Key value:1Key name: b2Key name: c3
Copy the code

Note:

  • The for in method not only iterates through all the enumerable properties of the current object, but also the properties on its prototype chain.

2. object.keys (), object.values (), Object.entries()

All three methods are used to iterate over an object. This returns an array of the given object’s own enumerable attributes (excluding the inherited and Symbol attributes) in the same order as the normal loop over the object. The three elements return the following values:

  • Object.keys() : Returns an array of Object keys;
  • Object.values() : Returns an array of Object keys and values;
  • Object.entries() : Returns an array of Object key names and key values.
let obj = { 
  id: 1.name: 'hello'.age: 18 
};
console.log(Object.keys(obj));   ['id', 'name', 'age']
console.log(Object.values(obj)); [1, 'hello', 18]
console.log(Object.keys(obj));   / / output: [[' id ', 1], [' name ', 'hello,'], [18] 'age,
Copy the code

Pay attention to

  • The array.keys () method returns all the values in the array as strings, meaning that keys that are not strings are converted to strings.
  • Attribute values in the resulting array are enumerable attributes of the object itself, excluding inherited attributes.

3. Object.getOwnPropertyNames()

Object. GetOwnPropertyNames () method and the Object. The keys (), is to accept an Object as a parameter, returns an array that contains all of the attributes of the Object itself. But it can return non-enumerable attributes.

let a = ['Hello'.'World'];
 
Object.keys(a) / / / "0", "1"
Object.getOwnPropertyNames(a) // ["0", "1", "length"]
Copy the code

Both methods can be used to count the number of attributes in an object:

var obj = { 0: "a".1: "b".2: "c"};
Object.getOwnPropertyNames(obj) / / / "0", "1", "2"]
Object.keys(obj).length / / 3
Object.getOwnPropertyNames(obj).length / / 3
Copy the code

4. Object.getOwnPropertySymbols()

Object. GetOwnPropertySymbols () method returns an array of Symbol attribute of the Object itself, not including the string attributes:

let obj = {a: 1}

// Add an unenumerable Symbol attribute to the object
Object.defineProperties(obj, {
 [Symbol('baz'] : {value: 'Symbol baz'.enumerable: false}})// Add an enumerable Symbol attribute to the object
obj[Symbol('foo')] = 'Symbol foo'
 
Object.getOwnPropertySymbols(obj).forEach((key) = > {
 console.log(obj[key]) 
})

// Symbol baz Symbol foo
Copy the code

5. Reflect.ownKeys()

Reflect.ownkeys () returns an array containing all the properties of the object itself. It is similar to Object.keys() in that object.keys () returns the property key but not the non-enumerable property, while reflect.ownkeys () returns all property keys:

var obj = {
	a: 1.b: 2
}
Object.defineProperty(obj, 'method', {
	value: function () {
	    alert("Non enumerable property")},enumerable: false
})

console.log(Object.keys(obj))
// ["a", "b"]
console.log(Reflect.ownKeys(obj))
// ["a", "b", "method"]
Copy the code

Note:

  • Object.keys() : returns an array of Object properties;
  • Reflect.ownkeys () : equivalentObject.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj).

Conclusion:

Object methods Iterate over the base properties Walk through the prototype chain Iterate over non-enumerable properties Traverse the Symbol
for in is is no no
Object.keys() is no no no
Object.getOwnPropertyNames() is no is no
Object.getOwnPropertySymbols() no no is is
Reflect.ownKeys() is no is is

Other traversal methods

1. for

The for loop is probably the most common type of loop. It consists of three expressions: declare loop variables, determine loop conditions, and update loop variables. These three expressions are separated by a semicolon. You can use temporary variables to cache the length of the array to avoid fetching the length repeatedly. The optimization effect is more obvious when the array is large.

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

During execution, conditions are judged before execution. The for loop can be used to iterate over groups of numbers, strings, class arrays, DOM nodes, and so on. You can change the original array.

2. while

The end condition in the while loop can be of any type, but will eventually be converted to a Boolean as follows.

  • Boolean: true is true, false is false;
  • String: Empty strings are false, all non-empty strings are true;
  • Number: 0 is false. Non-0 digits are true.
  • Null /Undefined/NaN: all false;
  • Object: All values are true.
let num = 1;
            
while (num < 10) {console.log(num);
    num ++;
}
Copy the code

While, like for, evaluates first and then executes. As long as the condition is true, the loop can always execute the code.

3. do / while

This method is executed before judging, and the do/while loop is executed at least once, even if the initial condition is not true.

let num = 10;
            
do
	{
    console.log(num);
    num--;
  }
while(num >= 0);
            
console.log(num); / / 1
Copy the code

It is not recommended to use do/while to iterate over groups of numbers.

4. for await of

for await… The of method is called an asynchronous iterator and is used primarily to iterate over asynchronous objects. It is an approach introduced in ES2018.

for await… The of statement creates an iteration loop over asynchronous or synchronous iterables, including Strings, arrays, array-like arrays, maps, sets, and custom asynchronous or synchronous iterables. This statement can only be used within async function:

function Gen (time) {
  return new Promise((resolve,reject) = > {
    setTimeout(function () {
       resolve(time)
    },time)
  })
}

async function test () {
   let arr = [Gen(2000),Gen(100),Gen(3000)]
   for await (let item of arr) {
      console.log(Date.now(),item)
   }
}
test()
Copy the code

Output result: