같은 자료 (비슷한 타입) 를 담는 자료 구조
(cf) 파이썬의 list와 비슷한 개념
- 하나의 변수에 여러 데이터를 관리할 수 있기 때문에, 코드의 가독성이 높아지고, 변수의 수를 줄여주고, 연산에 편리하다.
- 관련성 있는 데이터를 함께 변수에 저장하므로 데이터를 찾는데 용이하다.
객체: 연관된 행동이나 특징을 묶어 놓은 것을 말함.
ex)
토끼와 당근이 있다고 가정
토끼: 귀 2개, 동물, 귀엽다, 깡총깡총 뛴다
당근: 비타민 c 함유, 채소, 주황색
배열: 객체뿐만 아니라 정수 등 다양한 타입을 나열해 놓은 것을 말함.
ex)
토끼들을 순서대로 넣어둔 울타리
당근을 차곡차곡 정리한 바구니
( 객체와 다르게 배열은 순서가 있다는 것이 가장 큰 특징)
📢 다른 언어와 달리 자바스크립트는 다양한 자료형을 담을 수 있지만 실제로 프로그래밍을 할 때 사용하지 않는다!!
const arr1 = new Arrary(1,2,3); const arr2 = [1,2,3] //좀 더 간단
const animals = ['rabbit', 'wolf' ]; // 배열 선언 const.log(animals); // 배열 출력 const.log(animals.length); // 2 const.log(animals.[0];) // rabbit const.log(animals.[1]); // wolf const.log(animals.[2]);// undefined const.log(animals.[animal.length - 1 ]); // rabbit // 마지막 아이템을 찾고 싶을 때 자주 쓰임
const animals = [ 'rabbit', 'tiger', 'snake','elephant' ]
for (let i = o; i < animals.length; i++){ console.log(frutis[i]); }
# i가 0부터 length 까지 증가시키기
for (let animal of animals) { console.log(animal); }
📌 forEach: 배열의 값마다 내가 전달한 함수를 적용해주는 함수
animal.forEach(function (animal, index) { console.log(animal,index); } // 3개의 paremeter까지 받을 수 있음
축약 version - arrow function 사용
(이름이 없는 function은 arrow 함수 사용 가능)
animals.forEach((animal) => console.log(animal));
[ 'rabbit', 'tiger', 'snake','elephant']
배열의 가장 마지막에서부터 값 추가
animals.push('dog','cat'); console.log(animals); //[ 'rabbit', 'tiger', 'snake','elephant','dog','cat' ]
배열의 가장 마지막 값을 삭제한다.
fruits.pop(); console.log(animals); //['rabbit', 'tiger', 'snake']
배열의 맨 앞에서부터 값을 추가한다.
animals.unshift('pig','lion'); console.log(animals); //[ 'pig','lion','rabbit', 'tiger', 'snake','elephant']
배열의 맨 앞의 값을 삭제한다.
animals.shift(); console.log(animals); //['tiger', 'snake','elephant','dog']
📌TIP
shift와 unshift는 매우 느리게 작동
단순히 앞의 값을 삭제하거나 추가하는 개념이 아니라 뒤의 아이템들이
전부 이동해야 하기 때문
배열에서 원하는 안덱스의 값을 삭제와 추가 모두 가능
(1) 인덱스, 개수 지정
animals.splice(2,1) // 인덱스 2부터 1개를 삭제해라 console.log(animals); //[ 'rabbit', 'tiger','elephant'] //'snake' 삭제됨
(2) 인덱스만 지정
animals.splice(1) // 인덱스 1부터 뒤로 다 삭제 console.log(animals); //['rabbit'] 인덱스 0 이후 다 삭제
(3) 인덱스, 개수, 추가 값 지정
animals.splice(1,1,'hen','dolphin'); // 인덱스 1부터 1개 삭제하고 그 자리에 'hen','dolphin'을 넣어라 console.log(animals); //['rabbit','hen','dolphin', 'snake','elephant']
두개의 배열 합치기
const animals_2 = ['cow','sheep'] const newAnimals = animals.concat(animals_2); // animals에 animals_2를 연결 console.log(newAniamls); //[ 'rabbit', 'tiger', 'snake','elephant','cow','sheep']
[ 'rabbit', 'tiger', 'snake','elephant','tiger']
배열에서 처음으로 발견된 값(중복된 값이 있을 때)의 인덱스를 return
console.log(animals.indexOf('snake') // 2 console.log(animals.indexOf('cow') // 배열에 없는 값을 입력하면 -1이 반환된다
배열에서 마지막으로 발견된 값의 인덱스를 return
console.log(animals.lastindexOf('tiger')); // 4 //'인덱스 1의 tiger' 와 '인덱스 4 tiger' 중 마지막의로 발견된 값을 return
ture
false
console.log(animals.include('rabbit') //true console.log(animals.include('cow') //false