>  기사  >  웹 프론트엔드  >  JavaScript 주제 9: 배열에서 지정된 요소 찾기

JavaScript 주제 9: 배열에서 지정된 요소 찾기

coldplay.xixi
coldplay.xixi앞으로
2021-03-12 10:13:332906검색

JavaScript 주제 9: 배열에서 지정된 요소 찾기

Article Directory

    • 1. findIndex 및 findLastIndex
        • 1.1 findIndex
        • 1.2 findLastIndex
        • 1.3 findIndex 병합 및 찾기 La stIndex
    • 2. sortIndex
        • 2.1 Traversal
        • 2.2 Dichotomy
    • 3. indexOf 및 lastIndexOf
        • 3.1 indexOf 구현의 첫 번째 버전
        • 3.2 indexOf 및 lastIn의 일반적인 첫 번째 버전 dexOf
        • 3.3 indexOf 및 lastIndexOf 공통 2판
    • 참고
    • 는 맨 마지막에 작성

(무료 학습 추천 : javascript video tutorial)

1. findIndex 및 findLastIndex

1.1 findIndex

findIndex() 메소드는 제공된 테스트 함수를 만족하는 배열의 첫 번째 요소의 인덱스를 반환합니다. 해당 요소를 찾을 수 없으면 -1이 반환됩니다.

const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.findIndex(isLargeNumber));// expected output: 3

Implementation

Array.prototype.newFindIndex = function(callback) {
  const _arr = this;
  const len = _arr.length;
  for (let i = 0; i  element > 13;console.log(array1.newFindIndex(isLargeNumber));// 3

1.2 findLastIndex

마찬가지로 조건을 충족하는 첫 번째 메소드를 찾기 위해 되돌아볼 때 다음과 같이 작성할 수 있습니다.

Array.prototype.newFindlastIndex = function(callback) {
  const _arr = this;
  const len = _arr.length;
  for (let i = len - 1; i >= 0; i--) {
    if (callback(_arr[i], i, _arr)) {
      return i;
    }
  }
  return -1;};const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.newFindlastIndex(isLargeNumber));// 4

위 코드는 정방향 검색과 매우 유사합니다. 통과 조건을 변경합니다.

1.3 findIndex와 findLastIndex 병합

보시다시피, 루프 조건이 다르다는 점을 제외하면 두 메서드는 거의 동일합니다. lodash를 참조하여 두 메서드를 단순화하겠습니다

/**
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {boolean} [fromRight] 从右向左查找
 * @returns {number} 返回第一个符合条件元素的下标或-1
 */function baseFindIndex(array, predicate, fromRight) {
  const { length } = array;
  let index = fromRight ? length : -1; // 确定下标的边界

  while (fromRight ? index-- : ++index <p>그 형제를 살펴보겠습니다. code> 밑줄의 아이디어는 전달된 다양한 매개변수를 사용하여 다양한 함수를 반환하는 것입니다. <code>underscore</code> 的思路就是利用传参的不同,返回不同的函数。</p><pre class="brush:php;toolbar:false">function createIndexFinder(dir) {
  return function(array, predicate, context) {
    const { length } = array;
    var index = dir > 0 ? 0 : length - 1;

    for (; index >= 0 && index <p>关于 <code>findIndex</code> 我们就告一段落了~,再来看看新的场景和实现吧!</p><p><img src="https://img.php.cn/upload/article/000/000/052/c975230185fb614ade747b6d7f8688db-0.jpg" alt="JavaScript 주제 9: 배열에서 지정된 요소 찾기"></p><p><strong>二、sortIndex</strong></p><p>在一个排好序的数组中找到 <code>value</code> 对应的位置,即保证插入数组后,依然保持有序的状态。</p><pre class="brush:php;toolbar:false">const arr = [1, 3, 5];sortedIndex(arr, 0); // 0// 不需要插入arr

那么这个又该如何实现呢?

2.1 遍历

遍历大家都能想到,虽然它不一定最优解:

function sortIndex(array, value) {
  for (let i = 0; i  value) {
      return i;
    }
  }
  return array.length;}

2.2 二分法

function sortIndex(array, value) {
  let low = 0,
    high = array.length;
  while (low <p><strong>三、indexOf 和 lastIndexOf</strong></p>
  • indexOf():返回在数组中可以找到一个给定元素的第一个索引,如果不存在则返回-1。从数组的前面向后查找,从 fromIndex 处开始。
  • lastIndexOf() :返回指定元素在数组中的最后一个的索引,如果不存在则返回-1。从数组的后面向前查找,从 fromIndex 处开始。

3.1 indexOf 的第一版实现

function indexOf(array, value) {
  for (let i = 0; i <p>emmmm…在看过 findIndex 和 lastFindIndex 的实现后,indexOf 也要整整齐齐的啊~</p><h4>3.2 indexOf 和 lastIndexOf 通用第一版</h4><p>通过参数来创建不同的查找方法</p><pre class="brush:php;toolbar:false">function createIndexOf(dir) {
  return function(array, value) {
    let index = dir > 0 ? 0 : arr.length - 1;
    for (; index >= 0 && index <h4>3.3 indexOf 和 lastIndexOf 通用第二版</h4><p>这一次,我们允许指定查找位置,我们来看看 fromIndex 的作用:</p><blockquote><p>设定开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回 -1。<br> 如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即 -1 表示从最后一个元素开始查找,-2 表示从倒数第二个元素开始查找 ,以此类推。<br> 注意:如果参数中提供的索引值是一个负值,仍然从前向后查询数组。如果抵消后的索引值仍小于 0,则整个数组都将会被查询。其默认值为 0。</p></blockquote><pre class="brush:php;toolbar:false">function createIndexOf(dir) {
  return function(array, value, fromIndex) {
    // 设定开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回 -1。
    let length = array == null ? 0 : array.length;
    let i = 0;
    if (!length) return -1;
    if (fromIndex >= length) return -1;
    if (typeof fromIndex === "number") {
      if (dir > 0) {
        // 正序
        // 起始点>=0,沿用起始点,否则起始点为从后向前数fromIndex
        i = fromIndex >= 0 ? fromIndex : Math.max(length + fromIndex, 0);
      } else {
        // 倒序
        // 起始点>=0,沿用起始点,否则起始点为从后向前数fromIndex
        length =
          fromIndex >= 0
            ? Math.min(fromIndex + 1, length)
            : fromIndex + length + 1;
      }
    }
    // 起始下标
    for (
      fromIndex = dir > 0 ? i : length - 1;
      fromIndex >= 0 && fromIndex <p>写到这里我们在数组中查找元素就结束了,自己实现的和<code>loadsh</code>或<code>underscore</code>rrreee</p> <code>findIndex</code>는 끝났습니다~ 새로운 시나리오와 구현을 살펴보겠습니다! <p><img src="https://img.php.cn/upload/article/000/000/052/13e94628b4e8e9557aa00016b9d87ab1-1.jpg" alt="JavaScript 주제 9: 배열에서 지정된 요소 찾기"><img src="https://img.php.cn/upload/article/000/000/052/c975230185fb614ade747b6d7f8688db-0.jpg" alt="여기에 이미지 설명 삽입"></p><blockquote>
<p> 2. sortIndex <strong> </strong><a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript">정렬된 배열에서 <code>값</code>에 해당하는 위치를 찾으면 배열에 삽입한 후에도 순서가 유지됩니다. <strong>rrreee</strong>이를 달성하는 방법은 무엇입니까? </a><strong>2.1 순회</strong></p>순회는 반드시 최적의 솔루션은 아니지만 누구나 생각할 수 있습니다. </blockquote>rrreee🎜2.2 Dichotomy🎜rrreee🎜🎜3. indexOf 및 lastIndexOf🎜🎜🎜🎜<code>indexOf()</code>: 주어진 요소를 찾을 수 있는 배열의 첫 번째 🎜 인덱스를 반환하거나, 존재하지 않는 경우 -1을 반환합니다. fromIndex부터 배열의 앞부분부터 뒤로 검색합니다. 🎜🎜<code>lastIndexOf()</code>: 배열에 있는 지정된 요소의 🎜마지막 🎜 인덱스를 반환하거나, 존재하지 않는 경우 -1을 반환합니다. fromIndex부터 배열의 뒤에서부터 앞으로 검색합니다. 🎜🎜🎜3.1 indexOf 구현 첫 번째 버전🎜rrreee🎜으으으...findIndex와 lastFindIndex 구현을 보니 indexOf도 깔끔할 것 같아요~🎜🎜3.2 indexOf와 lastIndexOf의 첫 번째 버전은 보편적입니다🎜🎜매개변수를 통해 생성됨 다름 검색 방법🎜rrreee🎜3.3 indexOf 및 lastIndexOf Universal 두 번째 버전🎜🎜이번에는 검색 위치를 지정할 수 있습니다. fromIndex의 역할을 살펴보겠습니다. 🎜🎜🎜검색이 시작되는 위치를 설정합니다. 인덱스 값이 배열 길이보다 크거나 같으면 배열에서 검색을 수행하지 않고 -1이 반환된다는 의미입니다. <br> 매개변수에 제공된 인덱스 값이 음수 값인 경우 배열 끝에서부터의 오프셋으로 사용됩니다. 즉, -1은 마지막 요소부터 검색한다는 뜻이고, -2는 마지막 요소부터 검색한다는 의미입니다. 마지막 요소에서 두 번째, 등등. <br> 참고: 매개변수에 제공된 인덱스 값이 음수 값인 경우에도 배열은 앞에서 뒤로 쿼리됩니다. 오프셋 인덱스 값이 여전히 0보다 작은 경우 전체 배열이 쿼리됩니다. 기본값은 0입니다. 🎜🎜rrreee🎜이것이 배열의 요소 검색의 끝입니다. 우리가 구현한 것은 여전히 ​​<code>loadsh</code> 또는 <code>underscore</code>와 매우 다릅니다. 세 섹션 더 나은 코드 구현이 있으면 메시지 영역에 꼭 적어주세요~🎜🎜🎜🎜🎜🎜🎜관련 무료 학습 권장 사항: 🎜🎜🎜javascript🎜🎜🎜(동영상)🎜🎜🎜

위 내용은 JavaScript 주제 9: 배열에서 지정된 요소 찾기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제