js

[javascript] Array 개념

beaksul 2022. 9. 6. 17:22

1. 자료구조

 

비슷한 object끼리 묶는 것

 

 

2. Array(배열)

 

촘촘히 모여 있는 자료구조

0부터 시작하는 index를 가짐

동일한 type의 data를 넣는 것이 좋음

 

 

 

3. 배열 선언 방법

const arr1 = new Array();
const arr1 = [1, 2];

 

 

 

4. Index position

const fruits = ['apple','banana'];

console.log(fruits);
// (2) ["apple","banana"]
console.log(fruits.length);
// 2

// 배열의 첫번째 요소를 찾을 때
console.log(fruits[0]);
// apple

console.log(fruits[1]);
// banana
console.log(fruits[2]);
// undefined

// 배열의 마지막 요소를 찾을 때
console.log(fruits[fruits.length - 1]);
// banana

 

 

 

5. 배열 전체 출력 예시

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


for(let fruit of fruits){
	console.log(fruit);
}
// fruit이라는 변수에 fruits를 하나씩 대입해 출력


// callback함수
// forEach는 배열 안에 value마다 내가 전달한 함수를 출력해줌
fruits.forEach(function(fruit, index){
	console.log(fruit, index);
});
// apple 0 
// banana 1

fruits.forEach((fruit, index) => console.log(fruit, index));

 

 

- callback함수

value: _, index: _, array: _

 

 

6. 손쉽게 변수명 지정하기

cosnt arry = [1, 2, 3, 4];
const [one, two, three, four] = arry;
// 각각 변수명이 지정됨
// const [one,, three,] = arry;
// 생략도 가능