목차
集合类
帮助函数 (打印信息)
实现
测试
컬렉션 클래스
도움말 기능(정보 인쇄)
구현
테스트
检索类
运行
执行结果
拼接、附加和反转数组
添加、删除和追加值
实现 (简单实现)
扁平类
generator 类
总结
웹 프론트엔드 JS 튜토리얼 25가지 배열 메소드를 구현하여 이해(컬렉션)

25가지 배열 메소드를 구현하여 이해(컬렉션)

Dec 18, 2020 am 09:21 AM
javascript 정렬

이 글에서는 25가지 배열 메소드를 소개하고 있으며, 25가지 배열 메소드를 구현함으로써 이러한 배열 메소드를 효율적으로 이해하고 사용할 수 있습니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

25가지 배열 메소드를 구현하여 이해(컬렉션)

특정 배열에서 메서드를 사용하려면 [].Method 이름을 전달하면 됩니다. 이러한 메서드는 Array.prototype 개체에 정의됩니다. 여기서는 이러한 단계를 사용하지 않고 자체 버전을 정의하고 이러한 버전을 기반으로 구축하는 간단한 방법부터 시작하겠습니다. [].方法名即可,这些方法都定义在 Array.prototype 对象上。在这里,咱们先不使用这些相,反,咱们将从简单的方法开始定义自己的版本,并在这些版本的基础上进行构建。

没有比把东西拆开再重新组装起来更好的学习方法了。注意,当咱们的实现自己的方法时,不要覆盖现有的方法,因为有的库需要它们,并且这样也方便比较咱们自己的方法与原始方法的差异。

所以不要这样命名咱们自定义的方法:

    Array.prototype.map = function map() {
     // implementation
    };
로그인 후 복사

最好这样命名:

    function map(array) {
     // implementation
    }
로그인 후 복사

咱们也可以通过使用class关键字并扩展Array构造函数来实现咱们的方法,如下所示:

    class OwnArray extends Array {
     public constructor(...args) {
       super(...args);
     }
    
     public map() {
       // implementation
       return this;
     }
    }
로그인 후 복사

唯一的区别是,我们不使用数组参数,而是使用this关键字。

但是,我觉得 class 方式带来不必要的混乱,所以咱们采用第一种方法。

有了这个,咱们先从实现最简单的方法 forEach 开始!

集合类

.forEach

Array.prototype.forEach 方法对数组的每个元素执行一次提供的函数,而且不会改变原数组。

    [1, 2, 3, 4, 5].forEach(value => console.log(value));
로그인 후 복사

实现

    function forEach(array, callback) {
      const { length } = array;
      
      for (let index = 0; index < length; index += 1) {
        const value = array[index];
        callback(value, index, array)
      }
    }
로그인 후 복사

咱们遍历数组并为每个元素执行回调。这里需要注意的一点是,该方法没有返回什么,所以默认返回undefined

方法涟

使用数组方法的好处是可以将操作链接在一起。考虑以下代码:

    function getTodosWithCategory(todos, category) {
     return todos
       .filter(todo => todo.category === category)
       .map(todo => normalizeTodo(todo));
    }
로그인 후 복사

这种方式,咱们就不必将map的执行结果保存到变量中,代码会更简洁。

不幸的是,forEach没有返回原数组,这意味着咱们不能做下面的事情

    // 无法工作
    function getTodosWithCategory(todos, category) {
     return todos
       .filter(todo => todo.category === category)
       .forEach((value) => console.log(value))
       .map(todo => normalizeTodo(todo));
    }
로그인 후 복사

帮助函数 (打印信息)

接着实现一个简单的函数,它能更好地解释每个方法的功能:接受什么作为输入,返回什么,以及它是否对数组进行了修改。

    function logOperation(operationName, array, callback) {
     const input = [...array];
     const result = callback(array);
    
     console.log({
       operation: operationName,
       arrayBefore: input,
       arrayAfter: array,
       mutates: mutatesArray(input, array), // shallow check
       result,
     });
    }
로그인 후 복사

其中 mutatesArray 方法用来判断是否更改了原数组,如果有修改刚返回 true,否则返回 false。当然大伙有好的想法可以在评论提出呦。

    function mutatesArray(firstArray, secondArray) {
      if (firstArray.length !== secondArray.length) {
        return true;
      }
    
      for (let index = 0; index < firstArray.length; index += 1) {
        if (firstArray[index] !== secondArray[index]) {
          return true;
        }
      }
    
      return false;
    }
로그인 후 복사

然后使用logOperation来测试咱们前面自己实现的 forEach方法。

    logOperation(&#39;forEach&#39;, [1, 2, 3, 4, 5], array => forEach(array, value => console.log(value)));
로그인 후 복사

打印结果:

    {
      operation: &#39;forEach&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: undefined
    }
로그인 후 복사

.map

map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组。

实现

    function map(array, callback) {
      const result = [];
      const { length } = array;
      
      for (let index = 0; index < length; index +=1) {
        const value = array[index];
        
        result[index] = callback(value, index, array);
      }
    
      return result;
    }
로그인 후 복사

提供给方法的回调函数接受旧值作为参数,并返回一个新值,然后将其保存在新数组中的相同索引下,这里用变量 result 表示。

这里需要注意的是,咱们返回了一个新的数组,不修改旧的。

测试

    logOperation(&#39;map&#39;, [1, 2, 3, 4, 5], array => map(array, value => value + 5));
로그인 후 복사

打印结果:

    { 
      operation: &#39;map&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: [ 6, 7, 8, 9, 10 ]
     }
로그인 후 복사

.filter

Array.prototype.filter 过滤回调返回为false的值,每个值都保存在一个新的数组中,然后返回。

    [1, 2, 3, 4, 5].filter(number => number >= 3);
    // -> [3, 4, 5]
로그인 후 복사

实现

    function push(array, ...values) {
      const { length: arrayLength } = array;
      const { length: valuesLength } = values;
    
      for (let index = 0; index < valuesLength; index += 1) {
        array[arrayLength + index] = values[index];
      }
    
      return array.length;
    }
    --------------------------------------------------
    function filter(array, callback) {
     const result = [];
    
     const { length } = array;
    
     for (let index = 0; index < length; index += 1) {
       const value = array[index];
    
       if (callback(value, index, array)) {
         push(result, value);
       }
     }
    
     return result;
    }
로그인 후 복사

获取每个值并检查所提供的回调函数是否返回truefalse,然后将该值添加到新创建的数组中,或者适当地丢弃它。

注意,这里对result 数组使用push方法,而不是将值保存在传入数组中放置的相同索引中。这样,result就不会因为丢弃的值而有空槽。

测试

    logOperation(&#39;filter&#39;, [1, 2, 3, 4, 5], array => filter(array, value => value >= 2));
로그인 후 복사

运行:

    { 
      operation: &#39;filter&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: [ 2, 3, 4, 5 ] 
    }
로그인 후 복사

.reduce

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值reduce() 方法接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce() 的数组

确切地说,如何计算该值是需要在回调中指定的。来看呓使用reduce

모든 것을 분해하고 다시 조립하는 것보다 더 좋은 학습 방법은 없습니다. 자체 메소드를 구현할 때 일부 라이브러리에서 필요하므로 기존 메소드를 덮어쓰지 말고 자체 메소드와 원래 메소드의 차이점을 비교하는 것도 편리합니다. 🎜🎜그러므로 맞춤 메서드 이름을 다음과 같이 지정하지 마세요. 🎜
     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce((sum, number) => {
       return sum + number;
     }, 0) // -> 55
로그인 후 복사
로그인 후 복사
🎜다음과 같이 이름을 지정하는 것이 좋습니다. 🎜
    function reduce(array, callback, initValue) {
      const { length } = array;
      
      let acc = initValue;
      let startAtIndex = 0;
    
      if (initValue === undefined) {
        acc = array[0];
        startAtIndex = 0;
      }
    
      for (let index = startAtIndex; index < length; index += 1) {
        const value = array[index];
        acc = callback(acc, value, index, array)
      }
     
      return acc;
    }
로그인 후 복사
로그인 후 복사
🎜class 키워드를 사용하고 배열</code을 확장할 수도 있습니다. code> 생성자 메소드를 구현하려면 다음과 같습니다. 🎜<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'> logOperation(&amp;#39;reduce&amp;#39;, [1, 2, 3, 4, 5], array =&gt; reduce(array, (sum, number) =&gt; sum + number, 0));</pre><div class="contentsignin">로그인 후 복사</div></div><div class="contentsignin">로그인 후 복사</div></div>🎜 유일한 차이점은 배열 매개변수를 사용하는 대신 <code>this 키워드를 사용한다는 것입니다. 🎜🎜그러나 수업 방식이 불필요한 혼란을 가져오는 것 같아 첫 번째 방식을 채택합니다. 🎜🎜이제 가장 간단한 forEach 메서드 구현부터 시작해 보겠습니다! 🎜

컬렉션 클래스

🎜.forEach🎜🎜배열 .prototype.forEach 메소드는 원래 배열을 변경하지 않고 배열의 각 요소에 대해 제공된 함수를 한 번씩 실행합니다. 🎜
    { operation: &#39;reduce&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 15 
    }
로그인 후 복사
로그인 후 복사
🎜구현🎜
    [1, 2, 3, 4, 5, 6, 7].findIndex(value => value === 5); // 4
로그인 후 복사
로그인 후 복사
🎜배열을 반복하고 각 요소에 대해 콜백을 실행합니다. 여기서 주목해야 할 점은 이 메서드는 아무것도 반환하지 않으므로 기본적으로 undefine을 반환한다는 것입니다. 🎜🎜메서드 리플🎜🎜배열 메서드 사용의 장점은 작업을 서로 연결할 수 있다는 것입니다. 다음 코드를 생각해 보세요. 🎜
    function findIndex(array, callback) {
     const { length } = array;
    
     for (let index = 0; index < length; index += 1) {
       const value = array[index];
    
       if (callback(value, index, array)) {
         return index;
       }
     }
    
     return -1;
    }
로그인 후 복사
로그인 후 복사
🎜이렇게 하면 map의 실행 결과를 변수에 저장할 필요가 없어 코드가 더 간단해집니다. 🎜🎜안타깝게도 forEach는 원래 배열을 반환하지 않으므로 다음 작업을 수행할 수 없습니다.🎜
    logOperation(&#39;findIndex&#39;, [1, 2, 3, 4, 5], array => findIndex(array, number => number === 3));
로그인 후 복사
로그인 후 복사

도움말 기능(정보 인쇄)

🎜그런 다음 각 메서드의 기능(입력으로 받는 항목, 반환하는 항목, 배열 수정 여부)을 더 잘 설명하는 간단한 함수를 구현하세요. 🎜
    {
      operation: &#39;findIndex&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 2
    }
로그인 후 복사
로그인 후 복사
🎜mutatesArray 메서드는 원본 배열이 변경되었는지 확인하는 데 사용됩니다. 수정 사항이 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다. 물론, 좋은 아이디어가 있다면 댓글로 알려주시면 됩니다. 🎜
    [1, 2, 3, 4, 5, 6, 7].find(value => value === 5); // 5
로그인 후 복사
로그인 후 복사
🎜그런 다음 logOperation을 사용하여 이전에 구현한 forEach 메서드를 테스트하세요. 🎜
    function find(array, callback) {
     const index = findIndex(array, callback);
    
     if (index === -1) {
       return undefined;
     }
    
     return array[index];
    }
로그인 후 복사
로그인 후 복사
🎜인쇄 결과: 🎜
    logOperation(&#39;find&#39;, [1, 2, 3, 4, 5], array => find(array, number => number === 3));
로그인 후 복사
로그인 후 복사
🎜.map🎜🎜map 메소드는 원본을 제공합니다. 배열 요소의 각 요소는 콜백 함수를 순서대로 한 번씩 호출합니다. 각 콜백 실행 후 반환 값(정의되지 않음 포함)이 결합되어 새로운 배열을 형성합니다. 🎜

구현

    {
      operation: &#39;find&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 3
    }
로그인 후 복사
로그인 후 복사
🎜메서드에 제공된 콜백 함수는 이전 값을 매개변수로 받아들이고 새 값을 반환합니다. 이 값은 여기에서 동일한 인덱스 아래의 새 배열에 저장됩니다. 변수 result를 사용한다는 것은 의미합니다. 🎜🎜여기서 주목해야 할 점은 새 배열을 반환하고 이전 배열을 수정하지 않았다는 것입니다. 🎜

테스트

    [3, 2, 3].indexOf(3); // -> 0
로그인 후 복사
로그인 후 복사
🎜결과 인쇄: 🎜
    function indexOf(array, searchedValue) {
      return findIndex(array, value => value === searchedValue)
    }
로그인 후 복사
로그인 후 복사
🎜.filter🎜🎜 Array.prototype.filter 필터 콜백은 false 값을 반환하며, 각 값은 새 배열에 저장되어 반환됩니다. 🎜
    logOperation(&#39;indexOf&#39;, [1, 2, 3, 4, 5], array => indexOf(array, 3));
로그인 후 복사
로그인 후 복사

구현

    {
      operation: &#39;indexOf&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 2
    }
로그인 후 복사
로그인 후 복사
🎜각 값을 가져오고 제공된 콜백 함수가 true 또는 false를 반환하는지 확인합니다. 그런 다음 새로 생성된 배열에 추가되거나 적절하게 삭제됩니다. 🎜🎜여기에서는 push 메서드가 전달된 배열에 배치된 것과 동일한 인덱스에 값을 저장하는 대신 result 배열에 사용된다는 점에 유의하세요. 이렇게 하면 result에 버려진 값으로 인해 빈 슬롯이 없게 됩니다. 🎜

테스트

    [3, 2, 3].lastIndexOf(3); // -> 2
로그인 후 복사
로그인 후 복사
🎜실행: 🎜
    function lastIndexOf(array, searchedValue) {
      for (let index = array.length - 1; index > -1; index -= 1 ){
        const value = array[index];
        
        if (value === searchedValue) {
          return index;
        }
      }
      return  -1;
    }
로그인 후 복사
로그인 후 복사
🎜.reduce🎜 🎜reduce() 메서드는 함수를 누산기로 전달받으며 배열의 각 값(왼쪽에서 오른쪽으로)이 감소하기 시작하고 최종적으로 하나의 값. reduce() 메소드는 초기 값(또는 마지막 콜백 함수의 반환 값), 현재 요소 값, 현재 인덱스 및 Reduce()가 호출되는 배열의 네 가지 매개변수를 허용합니다. . 🎜🎜이 값을 정확히 계산하는 방법은 콜백에 지정되어야 합니다. reduce를 사용하는 간단한 예를 살펴보겠습니다. 숫자 집합을 합산하는 것입니다: 🎜
     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce((sum, number) => {
       return sum + number;
     }, 0) // -> 55
로그인 후 복사
로그인 후 복사

注意这里的回调接受两个参数:sumnumber。第一个参数总是前一个迭代返回的结果,第二个参数在遍历中的当前数组元素。

这里,当咱们对数组进行迭代时,sum包含到循环当前索引的所有数字的和因为每次迭代咱们都将数组的当前值添加到sum中。

实现

    function reduce(array, callback, initValue) {
      const { length } = array;
      
      let acc = initValue;
      let startAtIndex = 0;
    
      if (initValue === undefined) {
        acc = array[0];
        startAtIndex = 0;
      }
    
      for (let index = startAtIndex; index < length; index += 1) {
        const value = array[index];
        acc = callback(acc, value, index, array)
      }
     
      return acc;
    }
로그인 후 복사
로그인 후 복사

咱们创建了两个变量accstartAtIndex,并用它们的默认值初始化它们,分别是参数initValue0

然后,检查initValue是否是undefined。如果是,则必须将数组的第一个值设置为初值,为了不重复计算初始元素,将startAtIndex设置为1

每次迭代,reduce方法都将回调的结果保存在累加器(acc)中,然后在下一个迭代中使用。对于第一次迭代,acc被设置为initValuearray[0]

测试

    logOperation(&#39;reduce&#39;, [1, 2, 3, 4, 5], array => reduce(array, (sum, number) => sum + number, 0));
로그인 후 복사
로그인 후 복사

运行:

    { operation: &#39;reduce&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 15 
    }
로그인 후 복사
로그인 후 복사

检索类

有什么操作比搜索特定值更常见?这里有一些方法可以帮助我们。

.findIndex

findIndex帮助咱们找到数组中给定值的索引。

    [1, 2, 3, 4, 5, 6, 7].findIndex(value => value === 5); // 4
로그인 후 복사
로그인 후 복사

findIndex方法对数组中的每个数组索引0..length-1(包括)执行一次callback函数,直到找到一个callback函数返回真实值(强制为true)的值。如果找到这样的元素,findIndex会立即返回该元素的索引。如果回调从不返回真值,或者数组的length0,则findIndex返回-1

实现

    function findIndex(array, callback) {
     const { length } = array;
    
     for (let index = 0; index < length; index += 1) {
       const value = array[index];
    
       if (callback(value, index, array)) {
         return index;
       }
     }
    
     return -1;
    }
로그인 후 복사
로그인 후 복사

测试

    logOperation(&#39;findIndex&#39;, [1, 2, 3, 4, 5], array => findIndex(array, number => number === 3));
로그인 후 복사
로그인 후 복사

运行:

    {
      operation: &#39;findIndex&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 2
    }
로그인 후 복사
로그인 후 복사

.find

findfindIndex的唯一区别在于,它返回的是实际值,而不是索引。实际工作中,咱们可以重用已经实现的findIndex

    [1, 2, 3, 4, 5, 6, 7].find(value => value === 5); // 5
로그인 후 복사
로그인 후 복사

实现

    function find(array, callback) {
     const index = findIndex(array, callback);
    
     if (index === -1) {
       return undefined;
     }
    
     return array[index];
    }
로그인 후 복사
로그인 후 복사

测试

    logOperation(&#39;find&#39;, [1, 2, 3, 4, 5], array => find(array, number => number === 3));
로그인 후 복사
로그인 후 복사

运行

    {
      operation: &#39;find&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 3
    }
로그인 후 복사
로그인 후 복사

.indexOf

indexOf是获取给定值索引的另一种方法。然而,这一次,咱们将实际值作为参数而不是函数传递。同样,为了简化实现,可以使用前面实现的findIndex

    [3, 2, 3].indexOf(3); // -> 0
로그인 후 복사
로그인 후 복사

实现

    function indexOf(array, searchedValue) {
      return findIndex(array, value => value === searchedValue)
    }
로그인 후 복사
로그인 후 복사

测试

    logOperation(&#39;indexOf&#39;, [1, 2, 3, 4, 5], array => indexOf(array, 3));
로그인 후 복사
로그인 후 복사

执行结果

    {
      operation: &#39;indexOf&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: 2
    }
로그인 후 복사
로그인 후 복사

.lastIndexOf

lastIndexOf的工作方式与indexOf相同,lastIndexOf() 方法返回指定元素在数组中的最后一个的索引,如果不存在则返回 -1

    [3, 2, 3].lastIndexOf(3); // -> 2
로그인 후 복사
로그인 후 복사

实现

    function lastIndexOf(array, searchedValue) {
      for (let index = array.length - 1; index > -1; index -= 1 ){
        const value = array[index];
        
        if (value === searchedValue) {
          return index;
        }
      }
      return  -1;
    }
로그인 후 복사
로그인 후 복사

代码基本与findIndex类似,但是没有执行回调,而是比较valuesearchedValue。如果比较结果为 true,则返回索引,如果找不到值,返回-1

测试

    logOperation(&#39;lastIndexOf&#39;, [1, 2, 3, 4, 5, 3], array => lastIndexOf(array, 3));
로그인 후 복사

执行结果

    { 
      operation: &#39;lastIndexOf&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5, 3 ],
      arrayAfter: [ 1, 2, 3, 4, 5, 3 ],
      mutates: false,
      result: 5 
    }
로그인 후 복사

.every

every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试,它返回一个布尔值。

    [1, 2, 3].every(value => Number.isInteger(value)); // -> true
로그인 후 복사

咱们可以将every 方法看作一个等价于逻辑与的数组。

实现

    function every(array, callback){
      const { length } = array;
      
      for (let index = 0; index < length; index += 1) {
       const value = array[index];
       
        if (!callback(value, index, array)) {
          return false;
        }
      }
    
      return true;
    }
로그인 후 복사

咱们为每个值执行回调。如果在任何时候返回false,则退出循环,整个方法返回false。如果循环终止而没有进入到if语句里面(说明条件都成立),则方法返回true

测试

    logOperation(&#39;every&#39;, [1, 2, 3, 4, 5], array => every(array, number => Number.isInteger(number)));
로그인 후 복사

执行结果

    {
      operation: &#39;every&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: true 
    }
로그인 후 복사

.some

some 方法与 every 刚好相反,即只要其中一个为true 就会返回true。与every 方法类似,咱们可以将some 方法看作一个等价于逻辑或数组。

    [1, 2, 3, 4, 5].some(number => number === 5); // -> true
로그인 후 복사

实现

    function some(array, callback) {
     const { length } = array;
    
     for (let index = 0; index < length; index += 1) {
       const value = array[index];
    
       if (callback(value, index, array)) {
         return true;
       }
     }
    
     return false;
    }
로그인 후 복사

咱们为每个值执行回调。如果在任何时候返回true,则退出循环,整个方法返回true。如果循环终止而没有进入到if语句里面(说明条件都不成立),则方法返回false

测试

    logOperation(&#39;some&#39;, [1, 2, 3, 4, 5], array => some(array, number => number === 5));
로그인 후 복사

执行结果

    {
      operation: &#39;some&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: true
    }
로그인 후 복사

.includes

includes方法的工作方式类似于 some 方法,但是includes不用回调,而是提供一个参数值来比较元素。

    [1, 2, 3].includes(3); // -> true
로그인 후 복사

实现

    function includes(array, searchedValue){
      return some(array, value => value === searchedValue)
    }
로그인 후 복사

测试

    logOperation(&#39;includes&#39;, [1, 2, 3, 4, 5], array => includes(array, 5));
로그인 후 복사

执行结果

    {
      operation: &#39;includes&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: true
    }
로그인 후 복사

拼接、附加和反转数组

.concat

concat() 方法用于合并两个或多个数组,此方法不会更改现有数组,而是返回一个新数组。

    [1, 2, 3].concat([4, 5], 6, [7, 8]) // -> [1, 2, 3, 4, 5, 6, 7, 8]
로그인 후 복사

实现

    function concat(array, ...values) {
      const result = [...array];
      const { length } = values;
    
      for (let index = 0; index < length; index += 1) {
        const value = values[index];
        
        if (Array.isArray(value)) {
          push(result, ...value);
        } else {
          push(result, value);
        }
      }
    
      return result;
    }
로그인 후 복사

concat将数组作为第一个参数,并将未指定个数的值作为第二个参数,这些值可以是数组,也可以是其他类型的值。

首先,通过复制传入的数组创建 result 数组。然后,遍历 values ,检查该值是否是数组。如果是,则使用push函数将其值附加到结果数组中。

push(result, value) 只会向数组追加为一个元素。相反,通过使用展开操作符push(result,…value) 将数组的所有值附加到result 数组中。在某种程度上,咱们把数组扁平了一层。

测试

    logOperation(&#39;concat&#39;, [1, 2, 3, 4, 5], array => concat(array, 1, 2, [3, 4]));
로그인 후 복사

执行结果

    { 
     operation: &#39;concat&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: [ 1, 2, 3, 4, 5, 1, 2, 3, 4 ] 
    }
로그인 후 복사

.join

join() 方法用于把数组中的所有元素放入一个字符串,元素是通过指定的分隔符进行分隔的。

    [&#39;Brian&#39;, &#39;Matt&#39;, &#39;Kate&#39;].join(&#39;, &#39;) // -> Brian, Matt, Kate
로그인 후 복사

实现

    function join(array, joinWith) {
      return reduce(
        array,
        (result, current, index) => {
          if (index === 0) {
            return current;
          }
          
          return `${result}${joinWith}${current}`;
        },
        &#39;&#39;
      )
    }
로그인 후 복사

reduce的回调是神奇之处:reduce遍历所提供的数组并将结果字符串拼接在一起,在数组的值之间放置所需的分隔符(作为joinWith传递)。

array[0]值需要一些特殊的处理,因为此时result是一个空字符串,而且咱们也不希望分隔符(joinWith)位于第一个元素前面。

测试

    logOperation(&#39;join&#39;, [1, 2, 3, 4, 5], array => join(array, &#39;, &#39;));
로그인 후 복사

执行结果

    {
      operation: &#39;join&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: &#39;1, 2, 3, 4, 5&#39;
    }
로그인 후 복사

.reverse

reverse() 方法将数组中元素的位置颠倒,并返回该数组,该方法会改变原数组。

实现

    function reverse(array) {
      const result = []
      const lastIndex = array.length - 1;
    
      for (let index = lastIndex; index > -1; index -= 1) {
        const value = array[index];
        result[lastIndex - index ] = value
      }
      return result;
    }
로그인 후 복사

其思路很简单:首先,定义一个空数组,并将数组的最后一个索引保存为变量(lastIndex)。接着反过来遍历数组,将每个值保存在结果result 中的(lastIndex - index)位置,然后返回result数组。

测试

    logOperation(&#39;reverse&#39;, [1, 2, 3, 4, 5], array => reverse(array));
로그인 후 복사

执行结果

    {
      operation: &#39;reverse&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: [ 5, 4, 3, 2, 1 ]
    }
로그인 후 복사

添加、删除和追加值

.shift

shift() 方法从数组中删除第一个元素,并返回该元素的值,此方法更改数组的长度。

    [1, 2, 3].shift(); // -> 1
로그인 후 복사

实现

    function shift(array) {
      const { length } = array;
      const firstValue = array[0];
    
      for (let index = 1; index > length; index += 1) {
        const value = array[index];
        array[index - 1] = value;
      }
    
      array.length = length - 1;
    
      return firstValue;
    }
로그인 후 복사

首先保存数组的原始长度及其初始值,然后遍历数组并将每个值向下移动一个索引。完成遍历后,更新数组的长度并返回初始值。

测试

    logOperation(&#39;shift&#39;, [1, 2, 3, 4, 5], array => shift(array));
로그인 후 복사

执行结果

    {
      operation: &#39;shift&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 2, 3, 4, 5 ],
      mutates: true,
      result: 1
    }
로그인 후 복사

.unshift

unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。

    [2, 3, 4].unshift(1); // -> [1, 2, 3, 4]
로그인 후 복사

实现

    function unshift(array, ...values) {
      const mergedArrays = concat(values, ...array);
      const { length: mergedArraysLength } = mergedArrays;
    
      for (let index = 0; index < mergedArraysLength; index += 1) {
        const value = mergedArrays[index];
        array[index] = value;
      }
    
      return array.length;
    }
로그인 후 복사

首先将需要加入数组(作为参数传递的单个值)和数组拼接起来。这里需要注意的是values 放在第一位的,也就是放置在原始数组的前面。

然后保存这个新数组的长度并遍历它,将它的值保存在原始数组中,并覆盖开始时的值。

测试

logOperation(&#39;unshift&#39;, [1, 2, 3, 4, 5], array => unshift(array, 0));
로그인 후 복사

执行结果

    {
      operation: &#39;unshift&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 0, 1, 2, 3, 4, 5 ],
      mutates: true,
      result: 6
    }
로그인 후 복사

.slice

    slice()
로그인 후 복사

方法返回一个新的数组对象,这一对象是一个由 beginend 决定的原数组的浅拷贝(包括 begin,不包括end)原始数组不会被改变。

slice 会提取原数组中索引从 beginend 的所有元素(包含 begin,但不包含 end)。

    [1, 2, 3, 4, 5, 6, 7].slice(3, 6); // -> [4, 5, 6]
로그인 후 복사

实现 (简单实现)

    function slice(array, startIndex = 0, endIndex = array.length) {
     const result = [];
    
     for (let index = startIndex; index < endIndex; index += 1) {
       const value = array[index];
    
       if (index < array.length) {
         push(result, value);
       }
     }
    
     return result;
    }
로그인 후 복사

咱们遍历数组从startIndexendIndex,并将每个值放入result。这里使用了这里的默认参数,这样当没有传递参数时,slice方法只创建数组的副本。

注意:if语句确保只在原始数组中存在给定索引下的值时才加入 result 中。

测试

    logOperation(&#39;slice&#39;, [1, 2, 3, 4, 5], array => slice(array, 1, 3));
로그인 후 복사

执行结果

    {
      operation: &#39;slice&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4, 5 ],
      mutates: false,
      result: [ 2, 3 ]
    }
로그인 후 복사

.splice

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

首先,指定起始索引,然后指定要删除多少个值,其余的参数是要插入的值。

    const arr = [1, 2, 3, 4, 5];
    // 从位置0开始,删除2个元素后插入 3, 4, 5
    arr.splice(0, 2, 3, 4, 5);
    
    arr // -> [3, 4, 5, 3, 4, 5]
로그인 후 복사

实现

    function splice( array, insertAtIndex, removeNumberOfElements, ...values) {
      const firstPart = slice(array, 0, insertAtIndex);
      const secondPart = slice(array, insertAtIndex + removeNumberOfElements);
    
      const removedElements = slice(
        array,
        insertAtIndex,
        insertAtIndex + removeNumberOfElements
      );
    
      const joinedParts = firstPart.concat(values, secondPart);
      const { length: joinedPartsLength } = joinedParts;
    
      for (let index = 0; index < joinedPartsLength; index += 1) {
        array[index] = joinedParts[index];
      }
    
      array.length = joinedPartsLength;
    
      return removedElements;
    }
로그인 후 복사

其思路是在insertAtIndexinsertAtIndex + removeNumberOfElements上进行两次切割。这样,将原始数组切成三段。第一部分(firstPart)和第三部分(secondPart)加个插入的元素组成为最后数组的内容。

测试

    logOperation(&#39;splice&#39;, [1, 2, 3, 4, 5], array => splice(array, 1, 3));
로그인 후 복사

执行结果

    {
      operation: &#39;splice&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 5 ],
      mutates: true,
      result: [ 2, 3, 4 ]
    }
로그인 후 복사

.pop

pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。

实现

    function pop(array) {
     const value = array[array.length - 1];
    
     array.length = array.length - 1;
    
     return value;
    }
로그인 후 복사

首先,将数组的最后一个值保存在一个变量中。然后只需将数组的长度减少1,从而删除最后一个值。

测试

    logOperation(&#39;pop&#39;, [1, 2, 3, 4, 5], array => pop(array));
로그인 후 복사

执行结果

    {
      operation: &#39;pop&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [ 1, 2, 3, 4 ],
      mutates: true,
      result: 5
    }
로그인 후 복사

.push

push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。

    [1, 2, 3, 4].push(5); // -> [1, 2, 3, 4, 5]
로그인 후 복사

实现

    function push(array, ...values) {
      const { length: arrayLength } = array;
      const { length: valuesLength } = values;
    
      for (let index = 0; index < valuesLength; index += 1) {
        array[arrayLength + index] = values[index];
      }
    
      return array.length;
    }
로그인 후 복사

首先,我们保存原始数组的长度,以及在它们各自的变量中要添加的值。然后,遍历提供的值并将它们添加到原始数组中。

测试

    logOperation(&#39;push&#39;, [1, 2, 3, 4, 5], array => push(array, 6, 7));
로그인 후 복사

执行结果

    {
      operation: &#39;push&#39;,
      arrayBefore: [ 1, 2, 3, 4, 5 ],
      arrayAfter: [
        1, 2, 3, 4,5, 6, 7
      ],
      mutates: true,
      result: 7
    }
로그인 후 복사

.fill

当咱们想用一个占位符值填充一个空数组时,可以使用fill方法。如果想创建一个指定数量的null元素数组,可以这样做:

    [...Array(5)].fill(null) // -> [null, null, null, null, null]
로그인 후 복사

实现

    function fill(array, value, startIndex = 0, endIndex = array.length) {
     for (let index = startIndex; index < endIndex; index += 1) {
       array[index] = value;
     }
    
     return array;
    }
로그인 후 복사

fill方法真正做的是替换指定索引范围内的数组的值。如果没有提供范围,该方法将替换所有数组的值。

测试

    logOperation("fill", [...new Array(5)], array => fill(array, 0));
로그인 후 복사

执行结果

    {
      operation: &#39;fill&#39;,
      arrayBefore: [ undefined, undefined, undefined, undefined, undefined ],
      arrayAfter: [ 0, 0, 0, 0, 0 ],
      mutates: true,
      result: [ 0, 0, 0, 0, 0 ]
    }
로그인 후 복사

扁平类

有时咱们的数组会变嵌套两到三层,咱们想要将它们扁,也就是减少嵌套的程度。例如,想将所有值都放到顶层。为咱们提供帮助有两个新特性:flatflatMap 方法。

.flat

flat方法通过可指定深度值来减少嵌套的深度。

    [1, 2, 3, [4, 5, [6, 7, [8]]]].flat(1); // -> [1, 2, 3, 4, 5, [6, 7, [8]]]
로그인 후 복사

因为展开的深度值是1,所以只有第一级数组是被扁平,其余的保持不变。

    [1, 2, 3, [4, 5]].flat(1) // -> [1, 2, 3, 4, 5]
로그인 후 복사

实现

    function flat(array, depth = 0) {
     if (depth < 1 || !Array.isArray(array)) {
       return array;
     }
    
     return reduce(
       array,
       (result, current) => {
         return concat(result, flat(current, depth - 1));
       },
       [],
     );
    }
로그인 후 복사

首先,我们检查depth参数是否小于1。如果是,那就意味着没有什么要扁平的,咱们应该简单地返回数组。

其次,咱们检查数组参数是否属于数组类型,因为如果它不是,那么扁化就没有意义了,所以只返回这个参数。

咱们们使用了之前实现的reduce函数。从一个空数组开始,然后取数组的每个值并将其扁平。

注意,我们调用带有(depth - 1)flat函数。每次调用时,都递减depth参数,以免造成无限循环。扁平化完成后,将返回值来回加到result数组中。

测试

    logOperation(&#39;flat&#39;, [1, 2, 3, [4, 5, [6]]], array => flat(array, 2));
로그인 후 복사

执行结果

    {
      operation: &#39;flat&#39;,
      arrayBefore: [ 1, 2, 3, [ 4, 5, [Array] ] ],
      arrayAfter: [ 1, 2, 3, [ 4, 5, [Array] ] ],
      mutates: false,
      result: [ 1, 2, 3, 4, 5, 6 ]
    }
로그인 후 복사

.flatMap

flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 和 深度值1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。

在上面的map方法中,对于每个值,只返回一个值。这样,一个包含三个元素的数组在映射之后仍然有三个元素。使用flatMap,在提供的回调函数中,可以返回一个数组,这个数组稍后将被扁平。

    [1, 2, 3].flatMap(value => [value, value, value]); // [1, 1, 1, 2, 2, 2, 3, 3, 3]
로그인 후 복사

每个返回的数组都是扁平的,我们得到的不是一个嵌套了三个数组的数组,而是一个包含9个元素的数组。

实现

    function flatMap(array, callback) {
     return flat(map(array, callback), 1);
    }
로그인 후 복사

首先使用map,然后将数组的结果数组扁平化一层。

测试

    logOperation(&#39;flatMap&#39;, [1, 2, 3], array => flatMap(array, number => [number, number]));
로그인 후 복사

执行结果

    {
      operation: &#39;flatMap&#39;,
      arrayBefore: [ 1, 2, 3 ],
      arrayAfter: [ 1, 2, 3 ],
      mutates: false,
      result: [ 1, 1, 2, 2, 3, 3 ]
    }
로그인 후 복사

generator 类

最后三种方法的特殊之处在于它们返回生成器的方式。如果你不熟悉生成器,请跳过它们,因为你可能不会很快使用它们。

.values

values方法返回一个生成器,该生成器生成数组的值。

    const valuesGenerator = values([1, 2, 3, 4, 5]);
    
    valuesGenerator.next(); // { value: 1, done: false }
로그인 후 복사

实现

    function values(array) {
     const { length } = array;
    
     function* createGenerator() {
       for (let index = 0; index < length; index += 1) {
         const value = array[index];
         yield value;
       }
     }
    
     return createGenerator();
    }
로그인 후 복사

首先,咱们定义createGenerator函数。在其中,咱们遍历数组并生成每个值。

.keys

keys方法返回一个生成器,该生成器生成数组的索引。

    const keysGenerator = keys([1, 2, 3, 4, 5]);
    
    keysGenerator.next(); // { value: 0, done: false }
로그인 후 복사

实现

    function keys(array) {
     function* createGenerator() {
       const { length } = array;
    
       for (let index = 0; index < length; index += 1) {
         yield index;
       }
     }
    
     return createGenerator();
    }
로그인 후 복사

实现完全相同,但这一次,生成的是索引,而不是值。

.entries

entry方法返回生成键值对的生成器。

    const entriesGenerator = entries([1, 2, 3, 4, 5]);
    
    entriesGenerator.next(); // { value: [0, 1], done: false }
로그인 후 복사

实现

    function entries(array) {
     const { length } = array;
    
     function* createGenerator() {
       for (let index = 0; index < length; index += 1) {
         const value = array[index];
         yield [index, value];
       }
     }
    
     return createGenerator();
    }
로그인 후 복사

同样的实现,但现在咱们将索引和值结合起来,并在数组中生成它们。

总结

高效使用数组的方法是成为一名优秀开发人员的基础。了解他们内部工作的复杂性是我所知道的最好的方法。

英文原文:https://dev.to/bnevilleoneill/understand-array-methods-by-implementing-them-all-of-them-iha

更多编程相关知识,请访问:编程教学!!

위 내용은 25가지 배열 메소드를 구현하여 이해(컬렉션)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

foreach 루프를 사용하여 PHP 배열에서 중복 요소를 제거하는 방법은 무엇입니까? foreach 루프를 사용하여 PHP 배열에서 중복 요소를 제거하는 방법은 무엇입니까? Apr 27, 2024 am 11:33 AM

PHP 배열에서 중복 요소를 제거하기 위해 foreach 루프를 사용하는 방법은 다음과 같습니다. 배열을 순회하고 요소가 이미 존재하고 현재 위치가 첫 번째 항목이 아닌 경우 삭제합니다. 예를 들어, 데이터베이스 쿼리 결과에 중복된 레코드가 있는 경우 이 방법을 사용하면 이를 제거하고 중복된 레코드가 없는 결과를 얻을 수 있습니다.

PHP 어레이 딥 카피(Array Deep Copy) 기술: 다양한 방법을 사용하여 완벽한 카피 달성 PHP 어레이 딥 카피(Array Deep Copy) 기술: 다양한 방법을 사용하여 완벽한 카피 달성 May 01, 2024 pm 12:30 PM

PHP에서 배열을 깊게 복사하는 방법에는 json_decode 및 json_encode를 사용한 JSON 인코딩 및 디코딩이 포함됩니다. array_map 및 clone을 사용하여 키와 값의 전체 복사본을 만듭니다. 직렬화 및 역직렬화를 위해 직렬화 및 역직렬화를 사용합니다.

PHP 배열 키 값 뒤집기: 다양한 방법의 성능 비교 분석 PHP 배열 키 값 뒤집기: 다양한 방법의 성능 비교 분석 May 03, 2024 pm 09:03 PM

PHP 배열 키 값 뒤집기 방법의 성능 비교는 array_flip() 함수가 대규모 배열(100만 개 이상의 요소)에서 for 루프보다 더 나은 성능을 발휘하고 시간이 덜 걸리는 것을 보여줍니다. 키 값을 수동으로 뒤집는 for 루프 방식은 상대적으로 시간이 오래 걸립니다.

데이터 정렬에 PHP 배열 그룹화 기능 적용 데이터 정렬에 PHP 배열 그룹화 기능 적용 May 04, 2024 pm 01:03 PM

PHP의 array_group_by 함수는 키 또는 클로저 함수를 기반으로 배열의 요소를 그룹화하여 키가 그룹 이름이고 값이 그룹에 속한 요소의 배열인 연관 배열을 반환할 수 있습니다.

PHP 배열 심층 복사 모범 사례: 효율적인 방법 발견 PHP 배열 심층 복사 모범 사례: 효율적인 방법 발견 Apr 30, 2024 pm 03:42 PM

PHP에서 배열 전체 복사를 수행하는 가장 좋은 방법은 json_decode(json_encode($arr))를 사용하여 배열을 JSON 문자열로 변환한 다음 다시 배열로 변환하는 것입니다. unserialize(serialize($arr))를 사용하여 배열을 문자열로 직렬화한 다음 새 배열로 역직렬화합니다. RecursiveIteratorIterator를 사용하여 다차원 배열을 재귀적으로 순회합니다.

PHP 배열 다차원 정렬 연습: 간단한 시나리오부터 복잡한 시나리오까지 PHP 배열 다차원 정렬 연습: 간단한 시나리오부터 복잡한 시나리오까지 Apr 29, 2024 pm 09:12 PM

다차원 배열 정렬은 단일 열 정렬과 중첩 정렬로 나눌 수 있습니다. 단일 열 정렬은 array_multisort() 함수를 사용하여 열별로 정렬할 수 있습니다. 중첩 정렬에는 배열을 순회하고 정렬하는 재귀 함수가 필요합니다. 실제 사례로는 제품명별 정렬, 판매량 및 가격별 복합 정렬 등이 있습니다.

PHP 배열 병합 및 중복 제거 알고리즘: 병렬 솔루션 PHP 배열 병합 및 중복 제거 알고리즘: 병렬 솔루션 Apr 18, 2024 pm 02:30 PM

PHP 배열 병합 및 중복 제거 알고리즘은 병렬 처리를 위해 원본 배열을 작은 블록으로 나누는 병렬 솔루션을 제공하며, 기본 프로세스는 중복 제거를 위해 블록의 결과를 병합합니다. 알고리즘 단계: 원본 배열을 동일하게 할당된 작은 블록으로 분할합니다. 중복 제거를 위해 각 블록을 병렬로 처리합니다. 차단 결과를 병합하고 다시 중복 제거합니다.

중복 요소를 찾는 데 있어 PHP 배열 그룹화 기능의 역할 중복 요소를 찾는 데 있어 PHP 배열 그룹화 기능의 역할 May 05, 2024 am 09:21 AM

PHP의 array_group() 함수를 사용하면 지정된 키로 배열을 그룹화하여 중복 요소를 찾을 수 있습니다. 이 함수는 다음 단계를 통해 작동합니다. key_callback을 사용하여 그룹화 키를 지정합니다. 선택적으로 value_callback을 사용하여 그룹화 값을 결정합니다. 그룹화된 요소 수를 계산하고 중복 항목을 식별합니다. 따라서 array_group() 함수는 중복된 요소를 찾고 처리하는 데 매우 유용합니다.

See all articles