TIL#2 - 배열의 매서드와 사용 방법

Daily Dev Blog .·2021년 11월 4일
0

TIL

목록 보기
2/6
post-thumbnail

🔖https://developer.mozilla.org/ko/docs/Web/JavaScript/ 를 인용하였음.

🔖 배열의 메서드 종류는 상당히 다양하며 추가사항은 array.method 를 참고하시면 됩니다. 이 글에서는 대표적으로 쓰이는 인스턴트 메서드 몇가지를 알아보려 합니다.

📌 1. array.slice()

slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

구문

arr.slice([begin[, end]])

slice() 메서드 안에 begin(배열 index의 시작점), end(배열 index의 끝점) 두개의 인자가 들어있으며 경우에 따라 end인자는 사용하지 않을 수 있습니다.

//ex)1
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let result = fruits.slice(3)
//expected output: ['Apple', 'Mango'] 
//end인자를 사용하지 않을 시 begin 인덱스부터 마지막 배열 요소까지 나타냄.

//ex)2
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let result = fruits.slice(1, 3)
//expected output: ['Orange','Lemon'] 
//end에 들어갈 index를 제외하고 추출

//ex)3
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let result = fruits.slice(-2)
//expected output: ['Apple', 'Mango']
//인덱스에 음수가 들어갈 시 마지막 배열의 요소에서 가져옴.

⚠️slice 메서드는 배열 내의 특정한 요소의 index 범위에 따라 새로운 배열을 리턴합니다. 원본 배열을 변형시키지 않기 때문에 이 메서드를 사용할 때는 slice 메서드를 적용한 새로운 변수를 선언해주어야 합니다.

📌 2. array.splice()

splice 메서드는 배열 내의 특정한 요소를 삭제하거나, 다른 요소로 대치하거나 새로운 요소를 추가할 때 사용하며 splice 메서드를 쓸 때는 인자의 순서에 주의해야 합니다.

구문

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

3개의 인자가 들어있으며 필요에 따라 하나의 인자만 사용할 수 있습니다.

//ex)1
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
let removed = myFish.splice(2);
// myFish is ["angel", "clown"]
// removed is ["mandarin", "sturgeon"]

//ex)2
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
let removed = myFish.splice(-2, 1);
// myFish is ["angel", "clown", "sturgeon"]
// removed is ["mandarin"]

📌 3. array.pop()

pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

구문

arr.pop()

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

📌 4. array.push()

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.

구문

arr.push(element1[, ...[, elementN]])

//ex)1
let sports = ['축구', '야구'];
let total = sports.push('미식축구', '수영');

console.log(sports); // ['축구', '야구', '미식축구', '수영']
//배열 요소 끝에 추가

//ex)2 (with arr.concat())
// 첫번째 배열에 두번째 배열을 합치기
let vegetables = ['설탕당근', '감자'];
let moreVegs = ['셀러리', '홍당무'];
// vegetables.concat(moreVegs); 하는 것과 동일하다.
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무']

📌 5. array.includes()

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별하며 true, false (boolean)를 반환합니다.

구문

arr.includes(valueToFind[, fromIndex])

//ex)
[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false (인덱스값이 배열의 길이를 넘어서면 false)
[1, 2, 3].includes(3, -1); // true	
//fromIndex 가 음수라면, 이 계산된 인덱스는 valueToFind 를 찾기 시작할 배열의 위치로 
//사용되기 위해 연산됩니다.

//ex)2
[1, 2, 3].includes(2, -100); // true
//계산된 인덱스가 -1 * array.length 보다 작거나 같다면, 전체 배열이 검색될 것입니다.


[1, 2, NaN].includes(NaN); // true (문자도 판별 가능)

📌 6. array.filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다. 어떤 요소도 테스트를 통과하지 못했으면 빈 배열을 반환합니다.

구문

arr.filter(callback, index, array)

세개의 인자를 가지며 첫번째 부분인 element 인자만 필수로 지정되어야하고 나머지는 선택적입니다. callback은 각 요소를 시험할 함수로 true를 반환하면 요소를 유지하고, false를 반환하면 버립니다.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

📌 7. new Set(arr)

Set객체는 요소의 값이 유일하기 위해 검사를 수행하기 때문에 중복된 값을 제거하고 싶을 때 사용합니다.

구문

let set = new Set(arr);

let pasta = ['tomato', 'basil', 'onion','chicken'];
let pizza = ['tomato', 'cheese', 'onion','olive','beef'];

let result = pasta.concat(pizza); //두 배열을 합친다.
let result_set = [...new Set(result)]; 
//동작 원리 : 배열을 set객체(object형태)로 저장 및 중복삭제 -> 다시 배열[]로 변환.

📌 8. array.toString()

toString() 메서드는 지정된 배열 및 그 요소를 나타내는 문자열을 반환합니다.

구문

arr.toString()

//ex)
const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"
profile
Better Than Yesterday🌳

0개의 댓글