The array extension method was only used in ES5

JSON and arrays

JSON data is stored in HTML, reducing the request to the server and storing multiple ITEMS of JSON data in the form of arrays: [{……},{……},{……}]

This creates a set of data structures (objects are quoted and [] stores multiple objects) called JSON. JSON data is an object, and JSON data sets are arrays

Each value in the array is called an element

ForEach () : traversal

1. forEach()

It is a way to iterate over a group of numbers: the forEach() method is used to call each element of the array and pass the element to the callback function.

 data = [1.2.3];
       data.forEach(myFunction);

       function myFunction(item) {
           var sum = 0;
           for (var i = 0; i < data.length; i++) {
               sum = sum + data[i];  //sum = 1 + 2 + 3
           }
           console.log(sum);
       }
Copy the code

Since there are three elements in data, we iterate over function three times and print 6 three times

ForEach () is the Array prototype above method (array.prototype) so this method is only used for arrays, not objects, etc

ForEach () executes function every time an element is iterated –> provides three arguments:

data.forEach(function(elem, index, ayyay){/ Array element, index, array being traversedconsole.log(this);
});
Copy the code

Elem: The element of the current array

Index: Index of the current element

Array: array being traversed

Because each value in an array is called an element, forEach () usually writes data[I] as elem and I as index and this refers to the window and forEach () has two arguments in parentheses, The second argument changes the this pointer inside the function

Var data = [‘ 1 ‘, ‘2’]; , there are two elements, so the following result is printed twice:

  <script>
        var data = ['1'.'2'];
        data.forEach(function (elem, index, ayyay) {
            console.log(this); }, {name: 'test'}); / returns: {name: "test"}
        
        
          var data = ['1'.'2'];
        data.forEach(function (elem, index, ayyay) {
            console.log(this);
        },1); / returnNumber {1}
       
        
          var data = ['1'.'2'];
        data.forEach(function (elem, index, ayyay) {
            console.log(this);
        }, false); / returnBoolean {false}
   
   
     var data = ['1'.'2'];
        data.forEach(function (elem, index, ayyay) {
            console.log(this);
        },undefined);      /Window {parent: Window, opener: null.top: Window, length: 0.frames: Windows,... } </script>Copy the code

Since this must refer to an object, the arguments 1, false, etc. force it to be an object (wrapping class knowledge), so the second argument null, undefined will not be successful

2. Rewriting the forEach () method

Overwrite: Write the principle of this method in detail

    <script>
        var data = [1.2.3];
        var fn = function (elem, index, array) {
            console.log(this);  // point to data, because data calls this method; Apply points to the second argument
        }

        Array.prototype.myForEach = function (fn) {
            var arr = this.// Since it is an array to call a custom method, this refers to that array. Declare a variable arr in the method to hold this
                len = arr.length,
                args2 = arguments[1] | |window; // If the second argument is passed, it is saved to args2, if not, args is saved to window


            for (var i = 0; i < len; i++) {
                fn.apply(args2, [arr[i], i, arr]); // The function fn is iterated every time,
                // Use apply to change the direction of this function. Fn points to window, and then apply points to args2, Sum below}}var a = 1;

        data.myForEach(fn, a); Number {1}
 Window {parent: Window, opener: null, top: Window, length: 0, frames: Window,... }
    </script>
Copy the code

Summary: forEach () has two functions:

  • Traversal: The array called has a few elements, traversal a few times
  • Call the second argument into the first argument function

3. Filter () : filter

The big difference with forEach () is that it returns a new array, that is, it does not change the original array:

   <script>
        var data = [{ 'name': '0'.'age': '18' }];

        var newArr = data.filter(function (elem, index, array) {
            return elem.name === '0';  // Return data if it is true, null if it is false

        })
        console.log(newArr);
    </script>
Copy the code

This method determines which data needs to be added to the new array by returning true or false: function is used to compare data, and data is assigned to newArr if it is the same as data

Override of the filter() method

<script>
    var data = [{ 'name': '0'.'age': '18'}, {'name': '0'.'age': '8' }, {'name': '1'.'age': '8'}];var fn = function (elem, index, array) {
    return elem.name === '0';
}

Array.prototype.myFilter = function (fn) {
    var arr = this,
        len = arr.length,
        args2 = arguments[1] | |window,
        newArr = [];

    for (var i = 0; i < len; i++) {
        fn.apply(args2, [arr[i], i, arr]) ? newArr.push(arr[i]) : ""; 
        // add arr[I], independent of args2
    }
    return newArr
}
var newARR = data.myFilter(fn, [{ 'name': 'jack'.'age': '100' }]);
console.log(newARR); / / o {' name ':' 0 ', 'age', '18'}, {' name ':' 0 ', 'age', '8'}
    </script>
Copy the code

Apply does not apply to fn’s function because the window is executed regardless of the number of second arguments as long as it matches fn’s statement. At the same time, the qualified item puts the array element arr[I] (only in data) into the new array (newarr.push (arr[I])), so the second parameter is not involved. It will be useful later for the arrow function to analyze this pointing and so on

4

The map() method returns a new array whose elements are the values processed by the call to the original array element. It doesn’t change the value of the original array

  <script>
        var data = [{ 'name': '0'.'age': '18' }];
        var newArr = data.map(function (elem, index, arr) {
            elem.name = this.name + elem.name;
            // this.name is the value of the second parameter, and this refers to the second parameter
            return elem;
        }, { 'name': '[JS front-end]' })
        console.log(newArr);     
    </script>
Copy the code

{name: “[JS front end]0”, age: “18”} : data.map (fn, args2)

2. Map () method rewrite

        var data = [{ 'name': '0'.'age': '18' }];
        Array.prototype.myMap = function (fn) {
            var arr = this,
                len = arr.length,
                arg2 = arguments[1] | |window,
                nArr = [],
                item;

            for (var i = 0; i < len; i++) {
                item = arr[i];
       nArr.push(fn.apply(arg2, [item, i, arr]));  // The only difference is the for loop, which determines the properties of the method
            }
            return nArr;
        }

        var fn = function (elem, index, Array) {
            elem.name = this.name + elem.name;
            return elem;
        }
        var newArr = data.myMap(fn, { name: '[JS front-end]' });
        console.log(newArr);

Copy the code

Output: {name: “[JS front-end]0”, age: “18”} So map can modify data and add data

In live.

The only difference between these overrides is the for loop, which determines the properties of the method