1. Declaration
~ 배열 만들기 첫번째 ~
const arr1 = new Array();
~ 배열 만들기 두번째 ~
const arr2 = [1, 2];
2. Index position
const fruits = ['사과', '바나나'];
console.log(fruits);
// 결과 : ['사과', '바나나']
해당 array배열의 index.length 를 구해보면,
console.log(fruits.length);
// 결과 : 2
array배열은 숫자 index를 전달하게 되면 그 index에 해당하는 value값을 받아올 수 있다.
console.log(fruits[0]); // 사과
console.log(fruits[1]); // 바나나
만약, index 밖에 있는 index를 접근하게 되면,
console.log(fruits[2]); // undefined
보통 배열의 첫번쨰 아이템을 찾을 때는 0을 많이 쓰며, 배열의 마지막 아이템을 찾을 때는,
console.log(fruits[fruits.length - 1])
// 마지막 index data에 접근할 수 있다.
3. Looping over an array
console.log(fruits.array);
// (2) [‘사과’, ‘바나나’]
a. for loop
for (let i =0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// 사과
// 바나나
b. for of
for(let fruit of fruits) {
// fruit이라는 변수에 fruits이라는 배열을 할당.
console.log(fruit);
}
// 사과
// 바나나
c. forEach
Example) array.
const fruits = ['사과', '바나나’];
fruits.forEach()
forEach 분석하기
forEach(callbackfn: (value: T, index: number, array: T[]) => void,
우리가 전달한 callback 함수를 value값 마다 호출해주고 callback 함수에는 총 세가지의 인자(value, index, array)가 들어온다는 뜻.
1. Value : callback함수 안의 value값이 전달되고,
2. Index : 그 value값이 들어있는 index가 들어오고,
3. Array : 전체적인 array배열도 전달을 받을 수가 있다.
thisArg?: any): void;
‘사과'가 들어있는 index가 나의 callback 함수로 들어오고,’ 바나나'와 '바나나가 들어있는 index[1]’ 가 callback 함수로 들어온다는 것을 알수 있음.
fruits.forEach(function () {
console.log('he');
});
// 결과 : he 가 2번 출력되었다.
// 해설 : 사과, 바나나 총 2개가 들어있기 때문에.
fruits.forEach(function (fruit, index, array) {
console.log(fruit);
});
// 사과
// 바나나
fruits.forEach(function (fruit, index, array) {
console.log(fruit, index);
});
// 사과 0
// 바나나 1
fruits.forEach(function (fruit, index, array) {
console.log(fruit, index, array);
});
위의 식을 더 간단하게 arrow function을 이용해서 작성할 수도 있다.
fruits.forEach((fruit) => { console.log(fruit)}); // 사과 // 바나나
"forEach는 array배열안에 들어있는 value값들 마다 내가 전달한 function함수를 출력한다."
4. Add, Delete, Copy
push( )
pop( )
unshift( )
shift( )
splice( )
concat( )
Example) array.
const fruits = ['사과', '바나나’];
fruits.forEach()
push( )
fruits.push('딸기', '복숭아');
console.log(fruits);
// (4) ['사과', '바나나', '딸기', '복숭아']
pop ( )
fruits.pop();
console.log(fruits);
// (3) ['사과', '바나나', '딸기']
// index 맨 뒤에 있던 value 값이 지워져있음을 확인할 수 있다.
unshift( )
fruits.unshift('키위', '레몬');
console.log(fruits);
// (5) ['키위', '레몬', '사과', '바나나', '딸기']
shift( )
fruits.shift();
console.log(fruits);
// (4) ['레몬', '사과', '바나나', '딸기']
여기서 중요한 tip.
splice( )
splice(start: number, deleteCount?: number): string[ ]
fruits = ['레몬', '사과', '바나나', '딸기'];
fruits.splice(1);
console.log(fruits);
// ['레몬']
원하는 index만 지정하고 몇개를 지울 건지 설정하지 않으면 지정한 index 부터 끝까지 지워버린다.
그렇다면, 원하는 index를 지정하고, 몇개를 지울건지도 설정해보자.
fruits = ['레몬', '사과', '바나나', '딸기'];
fruits.splice(1, 1);
// 원하는 index[1], 지우고 싶은 갯수(1) 설정.
console.log(fruits);
// (3) ['레몬', '바나나', '딸기'];
우리가 설정한 해당 index[1]가 우리가 설정한 갯수(1)에 따라 지워졌음을 알수있다.
지우고 싶은 index를 지정하고, 몇개를 지울건지도 설정하며, 또 다른 value를 추가할 수 있도록 해보자.
fruits = ['레몬', '사과', '바나나', '딸기'];
fruits.splice(1, 1, '복숭아', '키위');
console.log(fruits);
// 순서1. ['레몬', /* '사과' */ 지워짐 , '바나나', '딸기'];
// 순서2. ['레몬', /* '복숭아', '키위' */ 들어감 , '바나나', '딸기'];
// 결과 : (5) ['레몬', '복숭아', '키위', '바나나', '딸기'];
concat( )
concat(...items: ConcatArray<T>[]): T[ ];
fruits = ['레몬', '복숭아', '키위', '바나나', '딸기'];
const fruits2 = ['오렌지','라임'];
// 새로운 array를 만들어서
const newFruits = fruits.concat(fruits2);
// concat API를 이용하여 기존의 fruits array와 결합한뒤, 변수로 선언하면
console.log(newFruits);
// 결과 : (7) ['레몬', '복숭아', '키위', '바나나', '딸기', '오렌지', '라임'];
기존의 fruits[array]와 fruit[array]가 결합되었음을 알 수 있다.
5. Searching
Example) array.
const fruits = ['레몬', '복숭아', '키위', '바나나', '딸기', '오렌지', '라임']
indexOf
console.log(fruits.indexOf('복숭아'));
// 1
console.log(fruits.indexOf('바나나'));
// 3
만약에 특정 value값이 해당 array배열 밖에 있다면 ?
console.log(fruits.indexOf('코코넛'));
// -1
// 즉, array배열안에 해당하는 value값이 없을 때는 -1이 출력이 된다.
includes
console.log(fruits.includes('복숭아'));
// true
console.log(fruits.includes('코코넛'));
// false
lastIndexOf
fruits = ['레몬', '복숭아', '키위', '바나나', '딸기’];
// push() : index 제일 마지막 번쨰에 추가하는 API
fruits.push('레몬');
console.log(fruits);
// ['레몬', '복숭아', '키위', '바나나', '딸기', '레몬'];
// indexOf : 제일 첫번째로 해당하는 값을 만나면 그 값이 들어있는 첫번째 Index를 리턴하게 된다.
console.log(fruits.indexOf('레몬'));
// 0
// lastIndexOf : 제일 마지막으로 해당하는 값을 만나면 그 값이 들어있는 마지막 Index를 리턴하게 된다.
console.log(fruits.lastIndexOf('레몬'));
// 5
출처 : 드림코딩 by 엘리 유투브 채널의 자바스크립트 시리즈 영상을 기반으로 작성했습니다. https://youtube.com/playlist?list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2