JavaScript
6-1 Array 객체
리버윤
2023. 9. 14. 12:00
728x90
Array 객체란?
여러 개의 값을 담을 수 있는 자료구조이다. 배열은 순서가 있는 요소들의 집합으로, 각 요소는 인덱스를 사용하여 접근할 수 있다.
Array 객체를 사용하여 배열을 생성, 초기화하는 예시
// 빈 배열 생성
let numbers = [];
// 초기값을 가지는 배열 생성
let fruits = ['apple', 'banana', 'orange'];
// 다양한 자료형의 값들로 구성된 배열
let mixedArray = [1, 'hello', true];
// 인덱스를 사용하여 요소에 접근
console.log(fruits[0]); // 'apple' 출력
// 배열 길이 확인
console.log(fruits.length); // 3 출력
// 새로운 요소 추가
fruits.push('grape');
console.log(fruits); // ['apple', 'banana', 'orange', 'grape'] 출력
// 요소 제거
fruits.splice(1, 2);
console.log(fruits); // ['apple', 'grape'] 출력
- Array 객체의 함수
- concat() : 두개 이상의 배열을 결합하여 새로운 배열을 생성
let arr1 = [1,2];
let arr2 = [3,4];
let combinedArray= arr1.concat(arr2);
console.log(combinedArray) //[1 ,2 ,3 ,4]
- join() : 모든 배열 요소들을 문자열로 변환하여 결합하고 구분자로 구분한 후 반환
var elements=['Fire','Air','Water'];
var joinedString=elements.join('-');
console.log(joinedString) //"Fire-Air-Water"
- push() : 배열의 끝에 하나 이상의 요소를 추가
let fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // ['apple', 'banana', 'orange']
- unshift() : 배열의 시작 부분에 하나 이상의 요소를 추가
let fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // ['apple', 'banana', 'orange']
- pop() : 배열의 마지막 요소를 제거하고 해당 요소를 반환
let fruits = ['apple', 'banana', 'orange'];
let removedFruit = fruits.pop();
console.log(fruits); // ['apple', 'banana']
console.log(removedFruit); // 'orange'
- shift() : 배열의 첫 번째 요소를 제거하고 해당 요소를 반환
let fruits = ['apple', 'banana', 'orange'];
let removedFruit = fruits.shift();
console.log(fruits); // ['banana', 'orange']
console.log(removedFruit); // 'apple'
- splice() : 지정된 위치에서 하나 이상의 요소를 삭제하거나 새로운 요소를 추가
let numbers = [1, 2, 3, 4];
numbers.splice(1,2);
console.log(numbers); // [1,4]
numbers.splice(1,0,'a','b');
console.log(numbers); //[1,'a','b' ,4]
- slice() : 지정된 범위 내에서 원본 배열로부터 새로운 배열을 추
let numbers = [1, 2, 3, 4, 5];
let slicedNumbers = numbers.slice(1, 4);
console.log(slicedNumbers); // [2, 3, 4]
728x90