Array
[Declaration]
- 배열은 다양한 데이터타입을 담을 수 있다 하지만 여러 타입을 하나의 배열로 선언하는 것은 좋지 않은 방법이다.
'use strict';
// Array🎉
// 1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];
[Index position]
- 인덱스는 0부터 시작
// 2. Index position
const fruits = ['🍎', '🍌'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]); //undefined
console.log(fruits[fruits.length - 1]); //마지막배열요소 찾기, 바나나
console.clear();
[Looping over an array]
- for, for of, forEach(API가 정의된 곳으로 가서 가서 사용법 찾아보기, Command 클릭으로 이동)
// 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((fruit) => console.log(fruit));
[Addition, deletion, copy]
1. push : 배열의 끝에 추가
2. pop : 맨 마지막 요소 1개를 삭제
3. unshift : 배열의 맨 앞에 추가 , (1과 2보다 느림)
4. shift : 배열의 맨 앞 요소를 1개 삭제, (1과 2보다 느림)
5. splice : 지정된 위치의 요소를 삭제
6. concat : 두개의 배열을 합친다.
// 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 begining
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
// splice: remove an item by index position
fruits.push('🍓', '🍑', '🍋');
console.log(fruits);
fruits.splice(1, 1); //1번인덱스부타 1개만 삭제 , 개수 지정을 안해주면 1번부터 뒤로 다 삭제
console.log(fruits);
fruits.splice(1, 0, '🍏', '🍉'); // 첫번째 인덱스 부터 0개만 지우고 뒤의 요소들을 추가
console.log(fruits);
// combine two arrays
const fruits2 = ['🍐', '🥥'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);
[Searching]
1. indexOf : 해당 요소가 몇번째 인덱스인지 찾기
2. includes : 해당 요소가 배열에 있는지 true, false
3. lastIndexOf : 제일 마지막에 들어있는 요소의 인덱스 찾기
// 5. Searching
// indexOf: find the index
console.clear();
console.log(fruits);
console.log(fruits.indexOf('🍎'));
console.log(fruits.indexOf('🍉'));
console.log(fruits.indexOf('🥥'));
// includes
console.log(fruits.includes('🍉'));
console.log(fruits.includes('🥥'));
// lastIndexOf
console.clear();
fruits.push('🍎');
console.log(fruits);
console.log(fruits.indexOf('🍎')); //0
console.log(fruits.lastIndexOf('🥥')); //
Thanks for 드림코딩
'Front-end > Web' 카테고리의 다른 글
[JS] JSON 개념정리와 활용방법 (0) | 2021.08.27 |
---|---|
[JS] 10가지 배열함수들, Array APIs 총정리 (0) | 2021.08.27 |
[JS] 오브젝트 (0) | 2021.08.27 |
[JS] 클래스와 오브젝트의 차이점, 객체지향 언어 클래스 정리 (0) | 2021.08.27 |
[JS] Arrow Function, 함수의 선언과 표현 (0) | 2021.08.27 |
댓글