JavaScript find elements within an array

Demand: Find the array element 6 if there
let arr = [1, 3, 6, 5, 7, 6];

The method of 1, indexOf method

From left to right to find, find returns the index can not find or -1

let index1 = arr.indexOf(6);
console.log(index1);//2
Method 2, lastIndexOf method

Find right to left, returns the index to find, can not find or -1

  let index2 = arr.lastIndexOf(6);
 console.log(index2);//5
Method 3, includes the method

From left to right to find, returns true find, can not find the returns false

 let resulr = arr.includes(6);
console.log(resulr);//true
Method 4, the array dedicated method findIndex

findIndex method: a customized version of indexOf, returns the index to find, can not find or -1

let index3 = arr.findIndex(function (currentValue, currentIndex, currentArray) {
            if (currentValue === 6){
                return true;
            }
        });
console.log(index3);//2
The method, arrays find specific method

find method: returns the element value found, can not find the returns undefined

        let value = arr.find(function (currentValue, currentIndex, currentArray) {
            // console.log(currentValue, currentIndex, currentArray);
            if (currentValue === 6){
                return true;
            }
        });
        console.log(value);
The principle of the method find

You can refer to: through the array of articles in the bottom forEach implementation.

        Array.prototype.myFind = function (fn) {
            for (let i = 0; i < this.length; i++) {//this:谁调用就是谁。arr数组调用的就是这个数组。
                fn(this[i], i, this);
            }
        };
        arr.myFind(function (currentValue, currentIndex, currentArray) {
            console.log(currentValue, currentIndex, currentArray);
        });

Precautions: findIndex implemented method similar to the above method.

Guess you like

Origin blog.csdn.net/Cao_Mary/article/details/89680934