>웹 프론트엔드 >JS 튜토리얼 >JavaScript 배열 메서드, 내부(부분)

JavaScript 배열 메서드, 내부(부분)

Linda Hamilton
Linda Hamilton원래의
2025-01-22 02:29:09619검색

JavaScript Array Methods, Under the Hood (Part )

이 기사에서는 .map() 루프를 사용하여 해당 기능을 다시 만들어 일반적인 JavaScript 배열 메서드(.includes(), .concat(), .flat()for)를 설명합니다. for 루프는 덜 효율적이고 읽기 어려워 보일 수 있지만 기본 메커니즘을 이해하면 내장 배열 방법에 대한 더 깊은 이해를 제공합니다. 뛰어들어 보세요!


.map()

.map() 메서드는 기존 배열의 각 요소에 함수를 적용하여 새 배열을 생성합니다. 비어 있지 않은 요소만 처리하고 원래 배열은 변경되지 않은 채로 둡니다.

데이터 구조의 고객 이름 목록이 필요한 은행 애플리케이션을 생각해 보세요. .map()가 가장 효율적인 솔루션이지만 for 루프를 사용하여 이를 달성하는 방법을 살펴보겠습니다.

<code class="language-javascript">const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

// Using a 'for' loop:
function getAllClientNamesLoop(array) {
  const acctNames = [];
  for (const acct of array) {
    acctNames.push(acct.name);
  }
  return acctNames;
}

// Using .map():
function getAllClientNamesMap(array) {
  return array.map(acct => acct.name);
}

console.log(getAllClientNamesLoop(bankAccounts)); // Output: ['Susan', 'Morgan', 'Joshua', 'Candy', 'Phil']
console.log(getAllClientNamesMap(bankAccounts)); // Output: ['Susan', 'Morgan', 'Joshua', 'Candy', 'Phil']</code>

for 루프 접근 방식을 사용하려면 빈 배열을 만들고 반복적으로 이름을 푸시해야 합니다. .map() 방법이 훨씬 더 간결하고 읽기 쉽습니다.

.includes()

이 메서드는 배열에 특정 값이 포함되어 있는지 확인하여 true 또는 false을 반환합니다.

for 루프와 .includes():

를 사용하여 이를 보여주는 함수를 만들어 보겠습니다.
<code class="language-javascript">// Using a 'for' loop:
function doesArrayIncludeLoop(array, value) {
  let isIncluded = false;
  for (const elem of array) {
    if (elem === value) {
      isIncluded = true;
      break; // Optimization: Exit loop once value is found
    }
  }
  return isIncluded;
}

// Using .includes():
function doesArrayIncludeIncludes(array, value) {
  return array.includes(value);
}

console.log(doesArrayIncludeLoop([1, 1, 2, 3, 5], 6)); // Output: false
console.log(doesArrayIncludeIncludes([1, 1, 2, 3, 5], 3)); // Output: true</code>

for 루프 버전은 플래그를 초기화하고 반복하는 반면 .includes()은 직접적이고 깔끔한 솔루션을 제공합니다.

.concat()

이 방법은 두 개 이상의 배열을 하나의 새 배열로 병합합니다.

다음은 for 루프와 .concat()을 사용한 비교입니다.

<code class="language-javascript">// Using 'for' loops:
function concatArraysLoop(arr1, arr2) {
  const concatenatedArray = [...arr1, ...arr2]; //Spread syntax for conciseness
  return concatenatedArray;
}

// Using .concat():
function concatArraysConcat(arr1, arr2) {
  return arr1.concat(arr2);
}

console.log(concatArraysLoop([0, 1, 2], [5, 6, 7])); // Output: [0, 1, 2, 5, 6, 7]
console.log(concatArraysConcat([0, 1, 2], [5, 6, 7])); // Output: [0, 1, 2, 5, 6, 7]</code>

다시 말하지만, .concat()는 뛰어난 간결성과 가독성을 제공합니다.

.flat()

.flat() 메서드는 중첩 배열을 단일 수준 배열로 평면화합니다. 선택적 깊이 매개변수를 허용합니다.

두 가지 방법을 모두 사용하여 배열을 한 수준 깊이로 평면화해 보겠습니다.

<code class="language-javascript">// Using 'for' loops:
function flatArraysLoop(array) {
  const flattenedArray = [];
  for (const elem of array) {
    if (Array.isArray(elem)) {
      flattenedArray.push(...elem); //Spread syntax
    } else {
      flattenedArray.push(elem);
    }
  }
  return flattenedArray;
}

// Using .flat():
function flatArraysFlat(array) {
  return array.flat();
}

console.log(flatArraysLoop([1, 2, 3, [4, [5, 6]], 10])); // Output: [1, 2, 3, 4, [5, 6], 10]
console.log(flatArraysFlat([1, 2, 3, [4, [5, 6]], 10])); // Output: [1, 2, 3, 4, [5, 6], 10]</code>

for 루프를 사용하여 더 깊게 중첩된 배열을 평면화하면 .flat(depth)의 강력함과 단순성이 강조되면서 점점 더 복잡해집니다.


이 탐색은 JavaScript에 내장된 배열 메소드의 우아함과 효율성을 보여줍니다. 2부에서는 더 많은 배열 방법을 살펴보겠습니다. 여러분의 생각과 질문을 자유롭게 공유해주세요! (2부 링크는 여기에 있습니다)

위 내용은 JavaScript 배열 메서드, 내부(부분)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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