The principle and implementation of every method of array

Posted Jun 16, 20201 min read

1.every usage

Rookie tutorial:

The every() method is used to detect whether all elements of the array meet the specified conditions(provided by the function).
The every() method uses the specified function to detect all elements in the array:
If one element in the array is detected to be unsatisfactory, the entire expression returns false and the remaining elements will not be detected.
Returns true if all elements satisfy the condition.
Note:every() returns true for empty array detection.
Note:every() does not change the original array.

The first parameter of every is a callback function, which can accept three parameters, in order of the current element item, the index of the current element index and the array arr calling this method, the second parameter of every is an object, which can be This is bound as a callback function.

2. Realization of everyy

    Array.prototype.myEvery = function(cb, thisValue) {
            if(typeof cb !=='function') {
                throw new Error('The first parameter should be a function')
            }
            //empty array returns true
            if(!this.length) {
                return true
            }
            for(let i = 0; i <this.length; i++) {
                //If the return value of any callback function is false, it returns false, and every execution stops
                //Use the call method to bind this in the callback function
                if(!cb.call(thisValue, this[i], i, this)) {
                    return false;
                }
            }
            //If the result of the callback function is true after the traversal is executed, return true
            return true
        }
For personal understanding only, if there is any error, please correct me.
If it helps you, please like it!