Array.slice 대 Array.splice: 혼란 해소

PHPz
풀어 주다: 2024-08-09 14:33:07
원래의
252명이 탐색했습니다.

Array.slice vs. Array.splice: Clearing Up the Confusion

소개

JavaScript 개발자로서 저는 두 가지 Array 메소드를 완전히 파악하기가 다소 까다롭다는 것을 종종 발견했습니다.

  1. 배열.슬라이스
  2. Array.splice.

그래서 저는 이러한 방법을 자세히 알아보고 명확한 예를 들어 설명하기로 결정했습니다.

Syntax를 다시 쓰면

Array.slice

returns the deleted elements in a form of Array = Array.prototype.slice(startIndex, endIndex-1);
로그인 후 복사

Array.splice (P는 영구 - 항상 기억)

JavaScript의 splice 메소드는 기존 요소를 제거 또는 교체하거나 새 요소를 제자리에 추가

하여 배열의 내용을 수정합니다.

요소 구문 제거

returns the deleted elements in a form of Array = Array.prototype.splice(startIndex, endIndex-1); // permanent 

로그인 후 복사

요소 구문 추가

array.splice(startIndex, 0, item1, item2, ..., itemX);
로그인 후 복사

참고:-

  1. 원래 배열을 변경하고 삭제된 배열을 반환합니다.

  2. 추가 작업으로 작동하면 아무것도 제거하지 않으므로 []를 반환합니다.

몇 가지 예를 살펴보겠습니다.-

Q1. 연습 1 - 슬라이스를 사용하여 배열의 일부 가져오기: 1부터 10까지의 숫자 배열을 만듭니다. 슬라이스 메서드를 사용하여 4부터 8까지의 숫자가 포함된 새 배열을 가져옵니다.

const arr = Array.from(Array(10), (_, i) => i+1);
console.log('Array --> ', arr);
console.log('get a new array that includes numbers from 4 to 8 --> ', arr.slice(3, 8)); // Array.prototype.slice(startIndex, endIndex-1);

// [ 4, 5, 6, 7, 8 ]
로그인 후 복사

Q2. 연습 2 - 스플라이스를 사용하여 배열에서 요소 제거: 과일 배열을 만듭니다. splice 메소드를 사용하여 배열에서 "apple"과 "banana"를 제거합니다.

const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

fruits.splice(0, 2)// permanent

console.log('splice method to remove "apple" and "banana" from the array. --> ', fruits);

// [ 'orange', 'mango', 'kiwi' ]
로그인 후 복사

Q3. 연습 3 - 스플라이스를 사용하여 배열에 요소 추가: 색상 배열을 만듭니다. "빨간색" 뒤에 "분홍색"과 "보라색"을 추가하려면 스플라이스 방식을 사용하세요.

const colors = ['red', 'green', 'blue'];

const y = colors.splice(1, 0, "pink", "purple"); /
console.log(y); // [] see above to see why.
console.log('splice method to add "pink" and "purple" after "red" --> ', colors)

// [ 'red', 'pink', 'purple', 'green', 'blue' ]
로그인 후 복사

Q4. 연습 4 - 슬라이스와 스플라이스를 함께 사용: 'a'에서 'e'까지의 문자 배열을 만듭니다. 처음 세 글자의 새로운 배열을 얻으려면 슬라이스를 사용하십시오. 그런 다음 원래 배열에서 스플라이스를 사용하여 이러한 문자를 제거합니다.

const letters = ['a', 'b', 'c', 'd', 'e'];
const newSlice = letters.slice(0, 3);
const x = letters.splice(0, 3);
console.log(x);
console.log('slice to get a new array of the first three letters --> ', newSlice) // [ 'a', 'b', 'c' ]

console.log('Then use splice on the original array to remove these letters --> ', letters)[ 'd', 'e' ]
로그인 후 복사

질문이나 우려사항이 있으면 언제든지 연락해 주세요.

위 내용은 Array.slice 대 Array.splice: 혼란 해소의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!