본문 바로가기

■ 프로그래밍/JavaScript

배열(Array) (2) - 업데이트, 추가(push), 제거(pop), 배열 이어 붙이기(join, concat)

배열에 데이터를 추가하는 방법은 몇 가지가 있다. 

 

1. index

원하는 자리에 데이터(요소)를 바꾸고 싶다면 인덱스를 활용하면 된다. 

var score = ["A", "B", "C", "D", "F"];

score[4] = "E";
console.log(score); // output: ["A", "B", "C", "D", "E"]

인덱스 방법을 이용해서 제일 뒤 데이터에 추가할 수도 있다. 

var score = ["A", "B", "C", "D", "F"];

score[5] = "G";
console.log(score); // output: ["A", "B", "C", "D", "F", "G"]

인덱스를 이용한 방법은 배열의 길이가 적을 때는 상관 없지만, 수 십개의 데이터가 있을 경우 번거로울 수 밖에 없다.

이를 위해 자바스크립트에는 push 메소드로 배열에 새로운 요소를 추가할 수 있다. 

 

2. 배열.push()

push를 사용하면 배열의 맨 뒤에 새로운 데이터(요소)를 추가한다. 

var number = ["one", "two", "three"];
number.push("four", "five");
console.log(number); // output: ["one", "two", "three", "four", "five"]

 

3. 배열.pop()

반대로 pop을 사용하면 제일 마지막 데이터(요소)를 삭제한다. 

var number = ["one", "two", "three", "four", "five"];
number.pop();
console.log(number); // output: ["one", "two", "three", "four"]

단, pop()에 어떤 내용을 쓰든 배열의 제일 마지막 데이터를 삭제한다. 

 

4. 배열.join()

이 외에도 같은 배열 안의 내용을 이어서 보여주는 join 메소드와 서로 다른 배열을 이어 붙여 주는 concat 메소드가 있다. 

var today = [2020, 3, 3]
console.log(today.join('/')); // output: 2020/3/3

 

5. 배열.concat()

var product = ["Mask", "Alcohol", "Corona"];
var number = [200, 100, 19];

console.log(product.concat(number)); // output: ["Mask", "Alcohol", "Corona", 200, 100, 19]