How to elegantly write a "find the specified element in the array"

Digression

Let me talk a little off topic first.

Since the underscore series of interpretation articles started on May 16th, 160+ stars have been received so far. I would like to thank you for your support here, and will continue to work hard to share the dry goods in the source code. I have a private message from a friend that I haven’t seen the update for several days. Please forgive me. After all, I regard it as one of this year’s plans, and I usually have to go to work and can only use my free time. The quality requirements of the article are relatively high. If it is a uniform flow article, the reader will not learn anything, and they will not be able to pass the level. In fact, if you are interested, you should be able to find that the full-text comments of the source code underscore-1.8.3 have been updated (the number of comment lines has almost broken 1000).

Main

Closer to home, in the last chapter we ended the Object extension method part, and today we will start to interpret the Array part extension method. In fact, the array in JavaScript is my favorite type. It can simulate data structures such as stacks and queues. It can also insert elements (splice) at will. It is very flexible. Those who have done leetcode should have a deep understanding of this (here also by the way. Download my leetcode problem solution Repo

Today I want to talk about how to find elements in an array, corresponding to the .findIndex, .findLastIndex, .indexOf, .lastIndexOf and _.sortIndex methods in underscore.

Wait, is it a bit familiar? Yes, the indexOf method (ES5) and findIndex method (ES6) have been deployed in JavaScript. This is not introduced, you can learn by yourself.

Let's first look at the .findIndex and .findLastIndex functions. If you understand the Array.prototype.findIndex() method, it will be very easy. The function of .findIndex is to find the first element that satisfies a certain condition from an array, and .findLastIndex is to find the last one (or search in reverse order).

Guess you like

Origin blog.51cto.com/15061401/2588736