JavaScript handwritten code issue 7 (rewrite array method 3) method for traversal

1. Why write code by hand?

In the daily development process, we often take it out and use it directly, never thinking about the underlying implementation logic of the code, but when I started to study some underlying things, I began to understand the underlying implementation ideas of each method and function in JavaScript , I think this can improve our code level and logical thinking very well.

2. Handwritten code

2.1 forEach

2.1.1 Basic use

The forEach() method is used to call each element of the array and pass the element to the callback function.

            let arr = [1, 2, 3];
            arr.forEach((item, index, arr) => {
    
    
                console.log(item, index, arr);
            });

insert image description here

2.1.2 Handwritten implementation

The output is consistent

            Array.prototype.myForEach = function (callback) {
    
    
              	if (typeof callback !== 'function') {
    
    
                    throw new Error('参数必须是一个函数');
                }
                for (let i = 0; i < this.length; i++) {
    
    
                    callback(this[i], i, this);
                }
            };
            arr.myForEach(function (item, index, arr) {
    
    
                console.log(item, index, arr);
            });

2.2 map

2.2.1 Basic use

The map() method returns a new array whose elements are the processed values ​​of the original array elements after calling the function.
The map() method processes elements sequentially in the original array element order.

The original array will not change
and return a new array: add 1 to the original array

            let arr = [1, 2, 3, 4];
            let newArr = arr.map((item, index, arr) => {
    
    
                return item + 1;
            });
            console.log(newArr); // [2, 3, 4, 5]
            console.log(arr); // 不会改变原数组 [1, 2, 3, 4]

2.2.2 Handwritten implementation

            Array.prototype.myMap = function (callback) {
    
    
              	if (typeof callback !== 'function') {
    
    
                    throw new Error('参数必须是一个函数');
                }
                // 最终要返回的数组
                let result = [];
                for (let i = 0; i < this.length; i++) {
    
    
                    result.push(callback(this[i], i, this));
                }
                return result;
            };
            let newArr = arr.myMap((item, index, arr) => {
    
    
                return item + 1;
            });
            console.log(newArr); // [2, 3, 4, 5]
            console.log(arr); // 不会改变原数组 [1, 2, 3, 4]

2.3 filter

2.3.1 Basic use

The filter() method creates a new array whose elements are checked by checking all elements in the specified array that meet the criteria.
filter() does not alter the original array.

Returns the items in the array greater than 3

            let arr = [1, 2, 3, 4, 5];
            let newArr = arr.filter((item, index, arr) => {
    
    
                return item > 2;
            });
            console.log(newArr); // [3,4,5]
            console.log(arr); // [1,2,3,4,5]

2.3.2 Handwritten implementation

            Array.prototype.myFilter = function (callback) {
    
    
              	if (typeof callback !== 'function') {
    
    
                    throw new Error('参数必须是一个函数');
                }
                let result = [];
                for (let i = 0; i < this.length; i++) {
    
    
                    // 判断是否符合item > 2,符合则push到数组res里面返回
                    callback(this[i], i, this) && result.push(this[i]);
                }
                return result;
            };
            let newArr = arr.myFilter((item, index, arr) => {
    
    
                return item > 2;
            });
            console.log(newArr); // [3,4,5]
            console.log(arr); // [1,2,3,4,5]

2.4 every

2.4.1 Basic use

The every() method is used to check whether all elements of the array meet the specified condition (provided by the function). The every() method checks all elements
in the array using the specified function : if an element in the array is detected to be unsatisfactory, the entire expression returns false , and the remaining elements are not checked again. Returns true if all elements satisfy the condition .

            let arr = [1, 2, 3, 4, 5];
            let flag = arr.every((item, index, arr) => {
    
    
                return item > 4;
            });
            console.log(flag); // true

2.4.2 Handwritten implementation

            Array.prototype.myEvery = function (callback) {
    
    
              	if (typeof callback !== 'function') {
    
    
                    throw new Error('参数必须是一个函数');
                }
                for (let i = 0; i < this.length; i++) {
    
    
                    if (!callback(this[i], i, this)) {
    
    
                        return false;
                    }
                }
                return true;
            };
            let flag = arr.every((item, index, arr) => {
    
    
                return item > 4;
            });
            console.log(flag); // false

2.5 some

2.5.1 Basic use

The some() method is used to check whether the elements in the array meet the specified condition (provided by the function).
If one element satisfies the condition, the expression returns true , and the remaining elements will not be checked again.
Returns false if no element satisfies the condition .

2.5.2 Handwritten implementation

            Array.prototype.mySome = function (callback) {
    
    
                if (typeof callback !== 'function') {
    
    
                    throw new Error('参数必须是一个函数');
                }
                for (let i = 0; i < this.length; i++) {
    
    
                    if (!callback(this[i], i, this)) {
    
    
                        return false;
                    }
                }
                return true;
            };
            let flag = arr.mySome((item, index, arr) => {
    
    
                return item > 3;
            });
            console.log(flag);

2.6 reduce

2.6.1 Basic use

The reduce() method accepts a function as an accumulator, and each value in the array (from left to right) is initially reduced to a final value.
Syntax: `

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

The first parameter total : required. The initial value, or the return value after the calculation is completed.
The second parameter currentValue : Required. The current element
The third parameter currentIndex : optional. The index of the current element
The fourth parameter arr : optional. The array object to which the current element belongs.

Use an example to realize the accumulation of array elements

            let arr = [1, 2, 3, 4];
            let sum = arr.reduce((tol, cur) => {
    
    
                return (tol += cur);
            }, 0);
            console.log(sum); // 10

2.6.2 Handwritten implementation

            Array.prototype.myReduce = function (callback, InitialValue) {
    
    
                if (typeof callback !== 'function') {
    
    
                    throw new Error('传入第一个参数必须是函数');
                }
                const array = this;
                // 如果没有传InitaialValue初始值时,初始值默认为数组的第一项即array[0]
                let result = InitialValue || array[0];
                for (let i = 0; i < array.length; i++) {
    
    
                    // 如果没有传第二个参数InitialValue初始值,当前数组第一项就不在进入循环
                    if (!InitialValue && i == 0) {
    
    
                        continue;
                    }
                    result = callback(result, array[i], i, this);
                }
                return result;
            };
            let result = arr.myReduce((tol, cur, index, arr) => {
    
    
                return (tol += cur);
            }, 0);
            console.log(result); // 10

2.7 find

2.7.1 Basic use

The find() method returns the value of the first element of the array that satisfies the condition .

            let arr = [1, 2, 3];
            let flag = arr.find((item, index, arr) => {
    
    
                return item > 2;
            });
            console.log(flag); // 3

2.7.2 Handwritten implementation

            Array.prototype.myFind = function (callback) {
    
    
                if (typeof callback !== 'function') {
    
    
                    throw new Error('传入的参数必须是函数');
                }
                for (let i = 0; i < this.length; i++) {
    
    
                    if (callback(this[i], i, this)) {
    
    
                        return this[i];
                    }
                }
                return undefined;
            };
            let flag = arr.myFind((item, index, arr) => {
    
    
                return item > 2;
            });
            console.log(flag);

2.8 findIndex

2.8.1 Basic use

The findIndex() method returns the position of the first element of the array passed in a test condition (function) .

            let arr = [1, 2, 3, 4];
            let index1 = arr.findIndex((item, index, arr) => {
    
    
                return item == 3;
            });
            console.log(index1);

2.8.2 Handwritten code

            Array.prototype.myFindIndex = function (callback) {
    
    
                for (let i = 0; i < this.length; i++) {
    
    
                    if (callback(this[i], i, this)) {
    
    
                        return i;
                    }
                }
                return -1;
            };

            let index1 = arr.myFindIndex((item, index, arr) => {
    
    
                return item == 3;
            });
            console.log(index1);

2.9 flatmap

2.9.1 Basic use

The flatMap() method first maps each element using the map function, then compresses the result into a new array. It is almost the same as the flat with the depth value of 1 attached to the map . When traversing the original array without changing the map, after the operation is completed, if the element that has been operated is an array, a layer of flatmap will be flattened.

faltmap(callback,thisArg)

The first parameter callback: (item, i, arr) can be passed in for execution The
second parameter thisArg: This points to thisArg when executing callback

Code example:

            let arr = [1, 2, 3, 4, 5];
            let arr1 = arr.flatMap((item) => [item * 2]);
            console.log(arr1); // [2, 4, 6, 8, 10]
            console.log(arr); // [1, 2, 3, 4, 5] 原数组没有发生改变
            let arr2 = arr.flatMap((item) => [[item * 2]]);
            console.log(arr2); // 只能拍平一层 [[2], [4], [6], [8], [10]];
            console.log(arr); // [1, 2, 3, 4, 5]

2.9.2 Handwritten implementation


            Array.prototype.myFlatMap = function (callback, thisArg) {
    
    
                let newArr = [];
                for (let i = 0; i < this.length; i++) {
    
    
                    let res = callback.call(thisArg, arr[i], i, arr);
                    if (Array.isArray(res)) {
    
    
                        newArr.push(...res);
                    } else {
    
    
                        newArr.push(res);
                    }
                }
                return newArr;
            };
            let arr1 = arr.flatMap((item) => [item * 2]);
            console.log(arr1); // [2, 4, 6, 8, 10]
            let arr2 = arr.myFlatMap((item) => [[item * 2]]);
            console.log(arr2); // 只能拍平一层 [[2], [4], [6], [8], [10]];
Welcome everyone to discuss and study, thank you for your support

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131354476