프로그래머스 암호 해독 자바스크립트 | 배열 원소 추가/삭제하기 | push, unshift, pop, shift, splice

Chaeyeon Lee·2023년 5월 25일
0

🔅 1. 아이디어

문자열 cipher중 code번째 글자만 answer배열에 추가하고, 이걸 합쳐서 리턴해야겠다!


🧑‍💻 2. 내 코드

function solution(cipher, code) {
    let answer=[];
    for(let i=code; i<=cipher.length; i+=code){
        answer.push(cipher[i-1]);
    }
    return answer.join('');
}

🐣 3. 개념

(1) 배열 원소 추가 함수

📌 1) Array.prototype.push()

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

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// 4 =>배열의 새로운 길이를 반환!
console.log(animals);
// Array ["pigs", "goats", "sheep", "cows"] =>끝에 새로운 원소가 추가되었다

animals.push('chickens', 'cats');
console.log(animals);
// Array ["pigs", "goats", "sheep", "cows", "chickens", "cats"]

📌 2) Array.prototype.unshift()

unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환한다.

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// 5 =>배열의 새로운 길이를 반환!

console.log(array1);
// Array [4, 5, 1, 2, 3] => 맨 앞에 추가되었다!

📌 3) Array.prototype.splice()

splice() 개념
배열의 기존 요소를 삭제/교체하거나 새 요소를 추가하여 원본배열의 내용을 변경한다. 그리고 제거한 요소를 담은 배열을 반환함. 제거된 요소를 제외한 배열이 반환되는 것이 아니다!

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

start: 배열의 변경을 시작할 인덱스. 배열의 길이보다 큰 값이면 실제 시작 인덱스는 배열의 길이로 설정된다.
deleteCount(opt): 배열에서 제거할 요소의 수. 생략하면 start부터 끝까지 제거한다.
item(opt): 배열에 추가할 요소. 지정하지 않으면 splice()는 모든 요소를 제거하기만 한다.

var arr = ['a', 'b', 'c'];

arr.splice(2, 0, 'd'); // index 2 ('c')의 위치에 요소를 추가
// arr = ['a', 'b', 'd', 'c']

arr.splice(4, 0, 'e', 'f'); // index 4의 위치에 2개의 요소를 추가
// arr = ['a', 'b', 'd', 'c', 'e', 'f']

(2) 배열 원소 삭제 함수

📌 1) Array.prototype.pop()

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

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

console.log(plants.pop());
// "tomato" =>삭제한 마지막 요소를 반환한다!

console.log(plants);
// Array ["broccoli", "cauliflower", "cabbage", "kale"] =>마지막 요소가 삭제되었음을 볼 수 있다!

plants.pop();
console.log(plants);
// Array ["broccoli", "cauliflower", "cabbage"]

📌 2) Array.prototype.shift()

shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환한다.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(firstElement);
// 1 =>삭제한 첫 번재 요소를 반환한다!!
console.log(array1);
// Array [2, 3] =>첫 번째 요소가 삭제되었다!

0번째 위치의 요소를 제거하고 연이은 나머지 값들의 위치를 한 칸씩 앞으로 당긴다.

📌 3) Array.prototype.splice()

원하는 위치에서 하나 이상의 요소를 제거할 수 있다.

var arr = ['a', 'b', 'c', 'e', 'f'];

arr.splice(2, 1); // index 2 부터 1개의 요소('c')를 제거
// arr = ['a', 'b', 'e', 'f']

arr.splice(1, 2); // index 1 부터 2개의 요소('b', 'e')를 제거
// arr = ['a', 'f']

removed = arr.splice(1, 1); // 제거한 요소를 반환 받을 수 있음
// arr = ['a']
// removed = 'f'

또한 제거 후에 해당 위치에 새로운 요소를 추가할 수 있다.


(3) 배열의 길이를 동적으로 변경하여 배열 맨 끝의 요소를 추가/삭제하는 방법

var arr = ['a', 'b', 'c'];

arr[arr.length] = 'e'; // 배열의 끝에 요소를 추가
// arr = ['a', 'b', 'c', 'e']; 

arr.length = arr.length - 1; // 배열의 크기를 하나 줄인다
// arr = ['a', 'b', 'c']

arr[5] = 'g'; // index 5 에 요소를 추가, 빈요소([3],[4])는 undefined
// arr = ["a", "b", "c", undefined, undefined, "g"]


출처
https://gent.tistory.com/295

profile
프론트엔드 개발자 지망생

0개의 댓글