[자바스크립트] - Array 함수

kang gicheon·2023년 7월 17일

JavaScript

목록 보기
4/7
post-thumbnail

자바스크립트는 Array 객체에 다양한 함수를 제공하여 배열 데이터를 조작하고 처리하는 데 도움을 줍니다. 이 글에서는 자바스크립트의 주요 Array 함수들에 대해 설명하고, 각 함수의 예시 코드와 실행 방법에 대해 알아보겠습니다.

push()

push() 함수는 배열의 끝에 하나 이상의 요소를 추가합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange'];
fruits.push('grape');
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']

pop()

pop() 함수는 배열의 마지막 요소를 제거하고 반환합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(removedFruit); // 'orange'
console.log(fruits); // ['apple', 'banana']

shift()

shift() 함수는 배열의 첫 번째 요소를 제거하고 반환합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(removedFruit); // 'apple'
console.log(fruits); // ['banana', 'orange']

unshift()

unshift() 함수는 배열의 앞에 하나 이상의 요소를 추가합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange'];
fruits.unshift('grape', 'kiwi');
console.log(fruits); // ['grape', 'kiwi', 'apple', 'banana', 'orange']

splice()

splice() 함수는 배열의 특정 위치에서 요소를 추가하거나 제거합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 0, 'grape', 'kiwi');
console.log(fruits); // ['apple', 'grape', 'kiwi', 'banana', 'orange']

fruits.splice(2, 2);
console.log(fruits); // ['apple', 'grape', 'orange']

slice()

slice() 함수는 배열의 일부분을 추출하여 새로운 배열로 반환합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
const slicedFruits = fruits.slice(1, 4);
console.log(slicedFruits); // ['banana', 'orange', 'grape']

concat()

concat() 함수는 두 개 이상의 배열을 병합하여 새로운 배열을 반환합니다.
예시 코드:

const fruits = ['apple', 'banana'];
const vegetables = ['carrot', 'tomato'];
const combined = fruits.concat(vegetables);
console.log(combined); // ['apple', 'banana', 'carrot', 'tomato']

indexOf()

indexOf() 함수는 배열에서 특정 요소의 인덱스를 반환합니다. 요소가 없으면 -1을 반환합니다.
예시 코드:

const fruits = ['apple', 'banana', 'orange'];
const index = fruits.indexOf('banana');
console.log(index); // 1

const notFoundIndex = fruits.indexOf('kiwi');
console.log(notFoundIndex); // -1

위에서 소개한 함수들은 자바스크립트 Array 객체의 일부분입니다. Array 객체는 다양한 함수와 속성을 가지고 있으며, 이를 통해 배열 데이터를 효율적으로 다룰 수 있습니다.

profile
느리지만 깊게 개발을 공부합니다

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

정말 좋은 정보 감사합니다!

답글 달기