Writing in the front

Based on ES6, there are 12 traversal methods that do not change themselves.

ForEach, every, some, filter, Map, reduce, reduceRight,

And ES6 new methods Entries, find, findIndex, keys and values.

// The forEach method does not return the processed array
// Note that when a function argument in forEach is passed two arguments,
// The first argument is value, not key
var array = [1.3.5];
var sReturn = array.forEach((value, index, array) = > {
  array[index] = value;
});
console.log(array); / / [1, 3, 5]
console.log(sReturn); // undefined, 
// The return value is undefined
Copy the code
/ / every method
var o = {0:10.1:8.2:25.length:3};
var bool = Array.prototype.every.call(o,(value, index, obj) = > {
  return value >= 8;
},o);
console.log(bool); // true
Copy the code
/ / some methods
var array = [18.9.10.35.80];
var isExist = array.some((value, index, array) = > {
  return value > 20;
});
console.log(isExist); // true 
Copy the code
/ / the map method
// map 有{}的时候需要有return 没有{}的时候不需要有return
var array = [18.9.10.35.80];
array.map(item= > item + 1);
array.map((item) = > { return item + 1})
console.log(array);  // [19, 10, 11, 36, 81]
Copy the code
/ / filter method
var array = [18.9.10.35.80];
var array2 = array.filter((value, index, array) = > {
  return value > 20;
});
console.log(array2); / / [35, 80]
Copy the code
/ / reduce method
var array = [1.2.3.4];
var s = array.reduce((previousValue, value, index, array) = > {
  return previousValue * value;
},1);
console.log(s); / / 24
// ES6 is more concise
array.reduce((p, v) = > p * v); / / 24
// reduceRight method (the difference between reduceRight and reduceRight is the backward accumulation)
var array = [1.2.3.4];
array.reduceRight((p, v) = > p * v); / / 24
Copy the code

/ / entries
var array = ["a"."b"."c"];
var iterator = array.entries();
console.log(iterator.next().value); // [0, "a"]
console.log(iterator.next().value); // [1, "b"]
console.log(iterator.next().value); // [2, "c"]
console.log(iterator.next().value); 
// undefined, iterator at the end of the array,
// Undefined is returned after iteration
Copy the code
// find & findIndex
var array = [1.3.5.7.8.9.10];
function f(value, index, array){
  return value%2= =0;     // Return an even number
}
function f2(value, index, array){
  return value > 20;     // Return the number greater than 20
}
 console.log(array.find(f)); / / 8
console.log(array.find(f2)); // undefined
console.log(array.findIndex(f)); / / 4
console.log(array.findIndex(f2)); // -1
Copy the code
/ / keys
[...Array(10).keys()];    
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[...new Array(10).keys()]; 
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

/ / values
var array = ["abc"."xyz"];
var iterator = array.values();
console.log(iterator.next().value);//abc
console.log(iterator.next().value);//xyz
Copy the code

Note that some traversal methods do not return the array after processing, such as forEach; Some methods return the array after processing, such as filter. This is a detail you need to keep in mind !!!! So that you can answer correctly during the interview.

The Reduce method also needs to be paid attention to. Its parameters are complex and numerous. In general, some complicated logic processing can be easily solved by using Reduce. What problem can Reduce solve? Let’s look at the two parameters of reduce.

The first is callback (a function called in each item of the array that takes four arguments) :

PreviousValue (the value returned when the callback function was last called, or the initial value)

CurrentValue (array element currently being processed)

CurrentIndex (index of the array element currently being processed)

Array (array that calls the reduce() method)

Then there is the initialValue (the optional initialValue passed to previousValue the first time the callback function is called).

It may seem confusing to just rely on words, but let me give you an example to illustrate how powerful reduce is.

/* : arr = [1,2,3,4
// The first method:
var arr = [1.2.3.4];
var sum = 0;
arr.forEach((e) = >{sum += e; });// sum = 10

// The second method
var arr = [1.2.3.4];
var sum = 0;
arr.map((obj) = > sum += obj);

// The third way
var arr = [1.2.3.4];
arr.reduce((pre,cur) = > {return pre + cur});
Copy the code

As can be seen from the above code, both forEach and Map can be used to realize array summation, where another variable “sum” needs to be defined and then summed up, and then the value of “sum” is finally looked at. Reduce can not only reduce the definition of a variable, but also directly return the final summation result. Is the problem solved easily?

So let’s combine a chestnut to see how reduce works.

var arr = [ 
  {name: 'brick1'}, 
  {name: 'brick2'}, 
  {name: 'brick3'}]Copy the code

Hope to return the name of each object in arR to the splice data of ‘Brick1, Brick2 & Brick3’, if using reduce how to achieve?

var arr =  [ {name: 'one'}, {name: 'two'}, {name: 'three'}]; arr.reduce((prev, current, index, array) = > {
  if (index === 0) {return current.name;
  } else if (index === array.length - 1) {return prev + '&' + current.name;
  } else {
    return prev + ', '+ current.name; }},' ');
// return result "one, two & three"
Copy the code
An array of classification Change your approach Don’t change your approach Traversal method (without changing itself)
ES5 Pop, push, reverse, Shift, splice, unshift Concat, Join, slice, toString, toLocaleString, indexOf, lastIndexOf ForEach, every, some, filter, Map, reduce, reduceRight
ES6 / 7 / 8 CopyWithin, the fill Includes, toSource Entries, find, findIndex, keys, values

All methods that insert elements, such as push and unshift, return the new array length.

All methods that remove elements, such as pop, Shift, and splice, return either the deleted element or an array of deleted elements.

Partial traversal methods such as forEach, every, some, filter, map, find, and findIndex all contain function(value,index,array){} and thisArg.

Let’s look at for in for of

For in

for … The value returned by the IN loop is the key-value name of the data structure (suitable for traversing objects). The key of the object returned by the iterator, and the key of the array returned by the iterator. for … The IN loop iterates not only over numeric key names, but also over values on the prototype and other manually added keys. Under special circumstances, for… The in loop iterates over the key names in what appears to be an arbitrary order.

const obj = {
        a: 1.b: 2.c: 3
        }
    for (let i in obj) {
        console.log(i)
        // a
        // b
        // c
    }
    for (let i of obj) {
        console.log(i)   // for can only iterate iterable
        // Uncaught TypeError: obj is not iterable
    }
Copy the code

 const arr = ['a'.'b'.'c']
    // for in loop
    for (let i in arr) {
        console.log(i)
        / / 0
        / / 1
        / / 2
    }
    
    // for of
 for (let i of arr) {
        console.log(i)
        // a
        // b
        // c
  }


for(let [key, value] ofmap){... }// Note that this is the form [key, value],
// write [1, 2], [3, 4]]
Copy the code
 const arr = ['a'.'b']
    // Manually add an attribute to the ARR array
    arr.name = 'qiqingfu'
    
    // The for in loop can iterate over the name of the key
    for (let i in arr) {
        console.log(i)
        // a
        // b
        // name
    }
Copy the code

In the Elements object, sort properties are stored in order, and the Properties property points to the Properties object, where regular properties are stored in the order they were created.

For characteristics of

The for of loop is used to get the values in a key-value pair, and the for in loop is used to get the key-names. A data structure that deploys the symbol. iterator property is considered to have an iterator interface, and the for of loop can be used. This object does not have a Symbol. Iterator property, so using for of would declare obj is not iterable for of. It can be used with break, continue, and return, meaning that the for of loop can exit at any time. Provides a unified interface to traverse all data structures.

The for of loop can be used for any data structure that has an Iterator interface.

  • An Array of Array
  • Map
  • Set
  • String
  • The arguments object
  • The Nodelist object is a collection of dom lists that you get

What if you want an object to use a for of loop? Use object.keys () to retrieve the key set of the Object, and then use for of to iterate over it

const obj = {
        a: 1.b: 2.c: 3
}
    
for (let i of Object.keys(obj)) {
        console.log(i)
        // a
        // b
        // c
}
for (let k of Object.values(obj)) {
        console.log(k)
        / / 1
        / / 2
        / / 3
}
Copy the code