Welcome✧˖*°࿐

코딩 💻 coding/JavaScript

자바스크립트 JS 공부 : 배열(Arrays)

러블리Hyeon 2025. 4. 25. 14:00

배열이란?

리스트에 저장된 다수의 값들을 포함하고 있는 하나의 객체

 

const shopping = ["bread","milk","cheese"];
shopping // [bread, milk, cheese]

 

다양한 데이터 유형을 배열에 넣을 수도 있다. 숫자, 문자열, 개체 등등

배열 항목의 접근과 수정

//접근
shopping[0];

//수정
shopping[0] = "tahini";
shooping; 
// ["tahini", "milk", "cheese" ]

배열의 갯수 알아내기

length 속성을 사용해서 문자열의 길이를 알아낸 것과 같은 방식으로 배열의 길이를 알아낼 수 있다

 

다중 배열

random[2][2];

 

대괄호 두개를 함께 연결해 다른 배열 안에 있는 배열 내부의 항목에 접근 가능하다

 

 


 

유용한 배열 메서드

  • split( ) : string 객체를 구분자로 이용해 여러 개의 문자열로 나누기. 아래와 같이 콤바 split를 이용하면 , 기준으로 문자열을 나눌 수 있게 됨.
var myData = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";
var myArray = myData.split(",");
myArray;
// ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle']

 

  • join( ) : 배열의 모든 요소를 쉼표나 지정된 구분 문자열로 구분해 연결하기
var myNewString = myArray.join(",");
myNewString;
// 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle'

 

  • push( ) : 배열의 끝에 명시된 요소를 추가하고 배열의 새로운 길이를 반환
  • pop( ) : 배열의 끝를 제거하고 그 요소를 반환
var myArray = [
  "Manchester",
  "London",
  "Liverpool",
  "Birmingham",
  "Leeds",
  "Carlisle",
];

myArray.push("Cardiff");
myArray; 
// ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle', 'Cardiff']

myArray.pop();
myArray;
// ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle' ]

 

  • unshift( ) : 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환
  • shift( ) : 배열의 맨 앞쪽을 제거하고, 제거된 요소를 반환
myArray.unshift("Edinburgh");
myArray;
// ['Edinburgh', 'Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle']

myArray.shift();
myArray;
//['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle']

 

 

반응형