* 배열(array)
1.배열 선언 (Declatation)
const arr1 = new Array(); // new 키워드 사용해 배열선언
const arr2 = [1, 2]; // [] 이용해서 배열 선언
2.Index position
const fruits = ['사과', '바나나'];
console.log(fruits); // 사과, 바나나 출력
console.log(fruits.length); // 2 출력 - furits 의 길이
console.log(fruits[0]); // 사과 출력 - fruits 의 0번째 index 출력
console.log(fruits[2]); // undefined 출력 - fruits 의 2번째 index 에 아무것도 없기 때문에
console.log(fruits[fruits.length - 1]); // 바나나 출력 furits의 마지막 데이터 찾는다
3.Looping over an array : 배열 안에 들어 있는 전체 데이터를 돌면서 출력
// for
for(let i = 0; i<fruits.length; i++){
console.log(fruits[i]);
}
// for of
for(let fruit of fruits){
console.log(fruit);
}
// forEach => callback함수를 받아온다
fruits.forEach(function (fruit, index){ // array 도 출력이 가능하다
console.log(fruit,index); // 사과 0
// 바나나 1 출력
});
// forEach => 함수 사용
fruits.forEach((fruit, index) => console.log(fruit,index));
4.Addtion, deletion, copy : 데이터 넣고, 빼고, 복사
// push : add an item to the end
fruits.push('딸기','복숭아'); // 배열의 맨뒤에 데이터 추가
// pop : remove an item from the end
fruits.pop(); // 배열의 맨뒤 데이터 삭제
// unshift : add and item to the benigging
fruits.unshift('딸기','레몬'); // 배열의 맨앞에 데이터 추가
// shift : remove an item from the benigging
fruits.shift(); // 배열의 맨앞에 데이터 삭제
// ** shift & unshift 는 pop & push 보다 엄청 느리다 : shift, unshift are slower than pop, push
// splice : remove an item by index position => 지울 index의 개수를 지정하지 않으면 지정한 index 부터 모든 index를 삭제한다
fruits.splice(1, 1); // (시작하는 index, 지울 index 갯수) => 1 index 1개만 지운다
fruits.splice(1, 1, '오렌지','수박'); // 지운 index 자리에 오렌지, 사과 데이터 추가
// combine two arrays : 두가지 배열 묶기
const fruits2 = ['배','코코넛'];
const newFruits = fruits.concat(fruits2); // 기존의 배열에 새로운 배열 연결
5.Searching
// indexof : find the index
console.log(fruits.indexOf('사과')); // 사과가 있는 index 번호를 알려준다
// includes
console.log(fruits.includes('사과')); // 배열에 데이터 중에 사과 라는 데이터 유무를 true, false로 리턴해준다
// lastIndexOf // 마지막에 있는 index 리턴해준다