하다보니

[JavaScript]배열 본문

프로그래밍 언어/JavaScript

[JavaScript]배열

claire 2022. 1. 15. 21:30

자료구조. 어떤 방식으로 데이터를 담느냐에 따라 타입이 다양하다. 

오브젝트와 자료구조의 차이. 토끼와 당근은 오브젝트. 서로 연관된 특징과 행동을 묶어놓는 것을 말한다. 비슷한 타입의 오브젝트들을 묶어 놓는 것을 자료구조라고 한다. 동일한 타입의 오브젝트만 담을 수 있다. 

자바스크립트는 타입이 동적으로 정의가 되기 때문에 다양한 타입을 담을 수 있다. 하지만 이러한 방식을 좋지 않다. 

 

한 배열 안에는 동일한 타입을 넣는다. 인덱스로 접근해서 삽입과 삭제가 편하다. 

 

1. 배열

 

- 배열의 선언과 원소 검색

// 1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];


// 2. Index position
const fruits = ['🍎', '🍌'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[fruits.length - 1]);    //마지막 원소 가져오는 법

 

-  for문으로 출력하는 법

// 3. Looping over an array
// print all fruits
// a. for
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

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

// c. forEach

fruits.forEach(function(fruit,index,array){			//forEach에 전달할 수 있는 인자 형태. 
  console.log(fruit,index);
});

fruits.forEach((fruit) => console.log(fruit));		//배열 안에 들어있는 value들마다 함수를 실행.

forEach는 콜백 함수를 받아온다. 

 

- 원소 추가, 삭제

// 4. Addtion, deletion, copy
// push: add an item to the end
fruits.push('🍓', '🍑');
console.log(fruits);

// pop: remove an item from the end
const poped = fruits.pop();
fruits.pop();
console.log(fruits);

// unshift: add an item to the benigging    
fruits.unshift('🍓', '🍋');
console.log(fruits);

// shift: remove an item from the benigging
fruits.shift();
fruits.shift();
console.log(fruits);

// note!! shift, unshift are slower than pop, push 
//뒤에서부터 넣고 빼는 것은 기존에 있는 데이터들에 영향을 주지 않지만 
//앞에 넣고 빼려면 기존의 모든 원소들을 이동해야하기 때문이다. 따라서 가능하면 pop과 push를 사용하자. 
//중간 원소를 넣고 빼는 것도 인덱스를 사용한다. 

// splice: remove an item by index position - 지정된 위치에서 원소를 삭제할 수 있다. 
//(시작 인덱스,지울 원소 갯수-optional)
fruits.push('🍓', '🍑', '🍋');
console.log(fruits);
fruits.splice(1);  //지울 갯수를 지정하지 않으면 시작 인덱스 이후의 모든 원소를 지운다. 
fruits.splice(1, 1); //인덱스 1만 삭제된다. 
console.log(fruits);
fruits.splice(1, 1, '🍏', '🍉');	//지울 원소 갯수 다음에 그 자리에 넣을 원소를 지정할 수도 있다. 
console.log(fruits);

// combine two arrays - 두가지 배열 묶기
const fruits2 = ['🍐', '🥥'];
const newFruits = fruits.concat(fruits2);	//concat으로 배열을 연결한다. 
console.log(newFruits);

- 원소 검색

// 5. Searching
// indexOf: find the index	- 해당 원소가 몇번째 인덱스에 있는지 리턴. 
console.clear();
console.log(fruits);
console.log(fruits.indexOf('🍎'));
console.log(fruits.indexOf('🍉'));
console.log(fruits.indexOf('🥥'));	//만약 배열에 없는 원소를 출력하면 -1이 출력된다. 

// includes	- 배열에 해당 원소가 있는지 t/f로 출력
console.log(fruits.includes('🍉'));  //true
console.log(fruits.includes('🥥'));  //false

// lastIndexOf
console.clear();
fruits.push('🍎');	//기존에 있는 원소와 똑같은 원소가 추가됨. 
console.log(fruits);
console.log(fruits.indexOf('🍎'));  //제일 첫번째 원소의 index 출력
console.log(fruits.lastIndexOf('🍎'));	//제일 마지막 원소에 해당하는 index 출력

출처 : 유튜브 드림코딩 by 엘리