Backend/JS & TS
자바스크립트 - part 1
퐁고
2023. 3. 23. 17:06
반응형
⭐️ 알고 가기
/*
<script defer src='파일명'></script>
<h1>javascript</h1>
*/
alert('실행창');
- js는 인터프리터 언어 컴파일러가 아님
- head에 js파일 연결하는데 defer 넣기( defer와 async) (defer는 동기적 async는 비동기적)
console.log → 출력
console.warn → 경고
console.error → 에러
변수
var, let, const
var: 지역변수, 전역 변수 개념도 없고 재할당도 가능해서 헷갈림
let: 재할당 가능
let num = 10;
num++
const: 재할당 불가
const person = {
name: 'kky',
age: 25,
}
자바 스크립트 타입
원시 타입
- number
- int
- float
- string
- boolean
- null
- object
- undefined
- const로 불가
- Symbol
const name = 'ky';
const age = 25;
const cm = 176.2;
const isMale = true;
const money = null;
let like; or const like = undefined;
console.log(typeof name);
console.log(typeof age);
console.log(typeof cm);
console.log(typeof isMale);
console.log(typeof money);
console.log(typeof like);
객체 타입
- object
- array
- function
문자열
const name = 'ky';
console.log('제 이름은' + name + '입니다');
console.log(`제 이름은 ${name} 입니다.`);
split
- 문자열을 배열로 바꿈
const aa = '안녕하세요 저는 김경영입니다.';
console.log(aa);
console.log(aa.split(' ');
join
- 배열을 문자열로 바꿈
const aa = '안녕하세요 저는 김경영입니다.';
console.log(aa);
arr = aa.split(' ');
console.log(arr.join(',');
replace
- 문자열 변경
const aa = '안녕하세요 저는 김경영입니다.';
console.log(aa.replace('저는','나는'));
substring
- 문자열 인덱스로 자르기
const aa = '안녕하세요 저는 김경영입니다.';
console.log(aa.substring(0,6);
toUpperCase, toLowerCase
- 문자열 대문자 소문자 변경
const k = 'hello my world';
console.log(k.toUpperCase());
배열, 객체
배열
const animal = ['dog','cat','lion'];
console.log(animal)
console.log(animal[0])
animal.push('tiger');
console.log(animal);
animal.shift();
console.log(animal);
- push - 뒤 추가
- unshift - 앞 추가
- pop - 뒤 삭제
- shift - 앞 삭제
Array.isArray(배열)
- 배열인지 아닌지 확인
console.log(Array.isArray(animal));
indexOf()
- 특정 요소의 인덱스 위치를 찾음
console.log(animal.indexOf('cat'));
splice(인덱스시작 번호, 삭제할 요소 개수) - 배열 특정 범위 삭제 및 요소 추가
- 인덱스 번호로 요소 삭제
- 기존 배열의 원본 값 변경
const animal = ['dog','cat','lion','monkey'];
console.log(animal.splice(1,2)); // cat,lion 잘라냄
console.log(animal); //dog, monkey 남아있음
animal.splice(1,2,'hi'); // cat lion 잘라내고 그 자리에 hi 추가
console.log(animal); // dog hi monkey
delete animal[1];
// 삭제는 하지만 배열 길이가 남아있음 별로임
slice(인덱스 시작 번호, 종료 인덱스 전까지) - 배열 특정 범위 복사
- 기존 배열의 원본값 유지
const animal = ['dog','cat','lion','monkey'];
const a = animal.slice(0,2);
console.log(a); // 인덱스 0에서 1까지 복사한 값
console.log(animal); // 원본 남아있음
sort
- 정렬
- 문자열을 기준으로 정렬하므로 정수형을 하려면 콜백 함수 사용
const num = [10,40,60,50];
console.log(num.sort((a,b) => a - b));
// b - a 내림차순
객체
const dog = {
name:'말티즈',
age: 10,
location : {
country: 'kr'
},
food: ['사료','개껌'],
}
접근법
console.log(dog.name);
console.log(dog['name']);
console.log(dog.location.country);
console.log(dog.location['country']);
console.log(dog['location'].country);
console.log(dog['location']['country']);
변경
dog.name = '포메';
console.log(dog.name);
dog.food[1] = '북어국';
console.log(dog.food);
dog.location.country = '한국';
console.log(dog.location.country);
추가
dog.bark = '왈왈';
console.log(dog);
JSON으로 바꿔주기
- json은 배열과 다르게 키값도 ‘’문자열 형태로 나온다.
- 즉, 배열처럼 키값에 접근할 수 없다.
const dogJSON = JSON.stringify(dog);
console.log(dogJSON);
JSON을 다시 Object로 바꾸기
const dogJSONParse = JSON.parse(dogJSON) ;
console.log(dogJSONParse);
반복문
기본형
const animal = [
{name: 'lion', weight: 200},
{name: 'pig', weight: 100},
{name: 'dog', weight: 60},
{name: 'rabbit', weight: 10},
];
for(let i = 0; i < animal.length; i++){
console.log(animal[i]);
}
let i = 0;
while(i < animal.length){
console.log(animal[i].name);
i++;
}
요즘 스타일 고급 반복문
for of
- 컬렉션 전용 반복 → 컬렉션 객체가 Symbol.iterator 속성을 지니고 있어야함 , 거의 사용을 안한다.
- 값을 반복함
for(i of animal){
console.log(i);
}
for in
- 모든 객체를 대상으로 순회 (배열보다는 객체)
- 키값을 반복, value값에 접근하는 방법은 제공 x
for(i in animal){
console.log(i);
// console.log(animal[i];
}
forEach - 자주 사용
- 배열 객체에서는 사용가능한 메서드
const animal = [
{name: 'lion', weight: 200},
{name: 'pig', weight: 100},
{name: 'dog', weight: 60},
{name: 'rabbit', weight: 10},
animal.forEach((i) => console.log(i.name));
animal.forEach((i, index) => console.log(index)); // animal의 인덱스를 반복
특정 배열 다시 만들기
map
- 배열을 다른 형태의 배열로 다시 만들 때 사용
- 원본 배열값은 유지
const animalName = animal.map((i) => i.name);
console.log(animalName);
const animalName2 = animal.map((i) => `animal is name ${i.name} weight ${i.weight}`);
console.log(animalName2);
filter
- 배열 안에서 특정 조건을 가진 아이템들만 뽑아내는 배열
const lightAnimal = animal.filter((i) => i.weight < 100);
console.log(lightAnimal);
reduce
- 가장 기본적 방법 - 배열 안 값들의 합
const hap = animal.reduce((past, current) => past + current.weight, 0);
console.log(hap);
// 0을 넣어준거는 초기값 past를 0으로 해주지 않으면 배열이 들어가 계산이 안된다.
조건문
if
- ==은 값만 ===은 타입도 검사 ===을 쓰도록 하자
- 조건의 참 거짓 유무 판단할 때 쓰임
const num = 10;
if (num == '10'){
console.log('값이 같다');
}
else if(num === '10'){
console.log('값과 타입이 같다');
}else{
console.log('다르다');
}
삼항 연산자
- 간단한 한 줄 짜리 조건문
const dog = '강아지';
const myDog = '강아지' === dog ? '맞아요': '아니야';
console.log(myDog);
Switch case
- 조건이 많을 때 사용
- 조건마다 break를 걸어줘야함
const dog = '말티즈';
switch(dog){
case '말티즈':
console.log('말티즈');
break;
case '포메':
console.log('포메');
break;
case '달마시안':
console.log('발견!');
break;
default:
console.log('없어요');
break;
}
함수
function add(a,b){
return a + b;
}
const add = function(a,b){
return a + b;
}
const add = (a,b) => {
return a + b;
} // 리턴문이 하나일 경우 괄호와 리턴 삭제 가능
생성자 함수
- 객체를 여러개 만들기 귀찮아서 씀
function Fruit(name, emoji){
this.name = name;
this.emoji = emoji;
this.display = () => {
console.log(`${this.name}는 ${this.emoji}`);
}
}
const banana = new Fruit('banana','🍌');
console.log(banana);
banana.display();
객체 만드는 법
객체 리터럴
const obj = {};
생성자 함수
function Fruit(name, emoji){
this.name = name;
this.emoji = emoji;
this.display = () => {
console.log(`${this.name}는 ${this.emoji}`);
}
}
const banana = new Fruit('banana','🍌');
console.log(banana);
banana.display();
object new 생성자 함수
const obj = new Object();
배열 만드는 법
배열 리터럴
const arr = []
Array 생성자 함수
const arr = new Array();