Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript TypedArray copyWithin() 메서드 사용법 완벽 정리

TypedArray.copyWithin() 메서드란?

copyWithin()은 TypedArray 객체가 제공하는 메서드로, 배열 내부의 요소를 다른 위치로 복사하는 기능을 합니다. 이 메서드는 배열 자기 자신 안에서 데이터를 복사하므로, 별도의 새로운 배열을 생성하지 않고도 특정 구간의 값을 이동시킬 수 있습니다.

이 메서드는 최대 세 개의 숫자형 매개변수를 받습니다.

  • target: 복사한 요소를 붙여넣을 시작 인덱스 (필수)
  • start: 복사할 데이터의 시작 인덱스 (선택)
  • end: 복사할 데이터의 끝 인덱스 (선택, 지정하지 않으면 배열 끝까지 복사)

문법(Syntax)

obj.copyWithin(target, start, end);

예제 1: 세 개의 매개변수 모두 사용하기

다음 예제는 Int32Array 타입 배열에서 인덱스 0부터 5 앞까지의 요소를 인덱스 5 위치로 복사하는 코드입니다.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55 ]);
      document.write("Contents of the typed array: "+int32View);
      int32View.copyWithin(5, 0, 5);
      document.write("<br>");
      document.write("Contents of the typed array after copy: "+int32View);
   </script>
</body>
</html>

실행 결과

Contents of the typed array: 21,64,89,65,33,66,87,55
Contents of the typed array after copy: 21,64,89,65,33,21,64,89

위 결과를 보면, 인덱스 0~4에 있던 값 21, 64, 89, 65, 33이 인덱스 5부터 차례대로 덮어써진 것을 확인할 수 있습니다.

예제 2: end 매개변수 생략하기

end 매개변수는 필수가 아닙니다. 세 번째 매개변수를 전달하지 않으면 배열의 끝까지 자동으로 복사됩니다.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55 ]);
      document.write("Contents of the typed array: "+int32View);
      int32View.copyWithin(5, 0);
      document.write("<br>");
      document.write("Contents of the typed array after copy: "+int32View);
   </script>
</body>
</html>

실행 결과

Contents of the typed array: 21,64,89,65,33,66,87,55
Contents of the typed array after copy: 21,64,89,65,33,21,64,89

정리 및 참고 사항

  • copyWithin()은 원본 배열을 직접 수정(mutate)하며, 수정된 배열을 반환합니다.
  • 복사 범위와 대상 범위가 겹쳐도 데이터가 올바르게 처리되며, 마치 먼저 복사한 후 붙여넣는 것처럼 동작합니다.
  • 음수 인덱스를 사용하면 배열 끝에서부터 계산됩니다. 예를 들어 -1은 마지막 요소를 의미합니다.
  • 일반 Array 객체에도 동일한 이름의 copyWithin() 메서드가 존재하며, 사용법은 거의 같습니다.