1 분 소요

Object와 자료구조의 차이점?

토끼와 당근이 있을 때 토끼와 당근 각각은 Object이다.
토끼: 눈, 코, 입, 뛴다, 먹는다
당근: 주황색, 비타민C
이렇듯 Object는 서로 연관된 특징과 행동을 묶어둔 것을 말함

토끼 여러마리 혹은 당근 여러개와 같이 비슷한 타입의 Object들을 묶어두는 것을 자료구조라고 함
다른 언어에서 자료구조는 동일한 타입의 오브젝트들만 담을 수 있지만, 자바스크립트는 dynamically typed language이기 때문에 다양한 종류의 데이터를 담을 수 있음 (하지만 그러지 않는게 좋음)

Array declaration

const arr1 = new Array();
const arr2 = [1,2]; // 더 흔하게 쓰는 방법!

Index position

const fruits = ['🍎', '🍌'];
console.log(fruits);
console.log(fruits[fruits.length - 1]); // 배열의 맨 마지막 요소 찾기

Looping

const fruits = ['🍎', '🍌'];

// for loop
for(let i=0; i< fruits.length; i++){
  console.log(fruits[i]);
}

// for of
for(let item of fruits){
  console.log(item);
}

// forEach
fruits.forEach(function (item, idx, arr) {
  console.log(item, idx, arr);
});

fruits.forEach(function (item, idx) { // 보통 arr는 잘 받지 않음
  console.log(item, idx);
});

// forEach -> arrow function
fruits.forEach((item) => console.log(item));

fruits.forEach(function (item, idx, arr) 출력 결과
스크린샷 2022-04-14 오전 2 52 49

추가, 삭제, 복제

const fruits = ['🍎', '🍌'];

fruits.push('🍓', '🍑'); // 마지막에 push
fruits.pop(); // 마지막 아이템을 pop

fruits.unshift('🍋'); // 처음에 push
fruits.shift(); // 처음 아이템을 pop

🚨 shift/unshift는 push/pop보다 매우 느림!

Splice

splice라는 API를 사용하면 지정된 위치의 데이터를 삭제할 수 있다.
사용법: splice(지우기 시작할 인덱스, 해당 인덱스부터 몇개를 지울건지)

const animals = ['🐶', '🐰', '🐯', '🐻', '🐥'];

animals.splice(3); // 몇개를 지울건지 설정하지 않으면 default는 4번 인덱스부터 모든 아이템을 삭제한다.
console.log(animals); // 🐶 🐰 🐯 

animals.splice(1,1); // 1번 인텍스부터 1개 삭제
console.log(animals); // 🐶 🐯 

animals.splice(0,1,'🦊','🐷'); // 0번 인텍스부터 1개 삭제하고 그 자리에 🦊 🐷  추가
console.log(animals); // 🦊 🐷 🐯 

animals.splice(1,0,'🐮'); // 데이터를 삭제하지 않고 1번 인덱스 자리에 🐮 추가
console.log(animals); // 🦊 🐮 🐷 🐯 

Combine two arrays

const people1 = ['😛', '🥰'];
const people2 = ['😜', '🥺'];

const newPeople = people1.concat(people2);

console.log(newPeople); // 😛' 🥰' 😜' 🥺'

검색

indexOf: 배열의 어떤 값이 몇번째 인덱스에 있는지 검색
includes: 배열에 아이템이 존재하는지 존재하지 않는지 검색

const animals = ['🐶', '🐰', '🐯'];
console.log(animals.indexOf('🐯')); // 2
console.log(animals.includes('🐨')); // false

lastIndexOf

배열에 같은 아이템이 둘 이상 존재한다면?

const animals = ['🐶', '🐰', '🐯', '🐶'];
console.log(animals.indexOf('🐶')); // 0 // 제일 처음 🐶의 인덱스를 출력
console.log(animals.lastIndexOf('🐶')); // 3 // 제일 마지막 🐶의 인덱스를 출력

📁 참고

DreamCoding



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기