구조분해할당
배열 속성을 해체하여 할당
선언만을 먼저 할 경우 const 대신에 let 사용해야 함
반복문 구조분해할당
for([i,j] of [[10, 20],[30, 40]]) {
console.log(i,j);
}
for([i,j,...k] of [[10, 20,300,1,2],[30, 40, 500,1]]) {
console.log(i,j,k);
}
for([i,j] of [[[10, 20],300],[[30, 40], 500]]) {
console.log(i,j);
}
일반변수 선언의 구조분해할당
좌변 갯수가 우변보다 많아도 할당을 안해준 경우이므로 undefined가 나옴
let a, b, c
[a,b] = [10,20];
let one1, two1, three1, four1;
[one1, two1, three1, ...four1] = '010-0000-1234-01-02-03'.split('-');
객체구조분해
할당 받을 변수의 이름과 프로퍼티 키가 동일해야 함
const human = {name: 'su', age: 10};
const {name, age} = human;
let data = {
name : 'lee',
age : 10,
money : 100
}
let {name, age} = data;
let {name, age, ...rest} = data;
const myPet = {nickname: 'star', age: 8};
const {nickname: 이름, age: 나이} = myPet;
함수
파선아실 - 파라미터 선언 아규먼트 실제 값
return - 반환
함수를 사용하는 이유
1. 재사용성
2. 유지보수
3. 구조 파악이 용이
function 함수이름(parameter1, parameter2...) {
실행코드...
return 반환값
}
function 안녕(){
console.log('hello')
return 10
}
안녕()
console.log(String(안녕()) + String(안녕()))
function 함수1 (a, b, c){
return a + b + c
}
function 함수2(a, b, ...c){
console.log(c)
return Math.max(...c)
}
함수2('hello', 'world', 10, 20, 30, 40)
function 함수3(a=10, b=20, c=30){
return a + b + c
}
console.log(함수3())
console.log(함수3(100))
console.log(함수3(100, 200))
console.log(함수3(100, 200, 300))
console.log(함수3(c=1000))
console.log(함수3(c=1000, a=2000))
function 함수4({
회원등급,
글쓰기,
글읽기,
채널관리,
백업,
소셜로그인여부
}){
console.log('함수기능')
console.log(회원등급, 글쓰기, 글읽기, 채널관리, 백업, 소셜로그인여부)
return
}
함수4({
회원등급: "Gold",
채널관리: false,
백업: "부분가능",
소셜로그인여부: true
})
function 함수4({
회원등급 = 'Gold',
글쓰기 = true,
글읽기 = true,
채널관리 = true,
백업 = '부분가능',
소셜로그인여부 = true
}){
console.log('함수기능')
console.log(회원등급, 글쓰기, 글읽기, 채널관리, 백업, 소셜로그인여부)
return
}
함수4({
회원등급 : 'Silver',
소셜로그인여부: true
})
재귀 함수
재귀함수 (Top-down, 분할정복) <-> 반복문 (Bottom-up)
종료 조건이 없으면 무한 반복!!!
순회를 돌지 않고 해결할 수 있으면 돌지 않고 해결
function factorial(n){
if (n <= 1){
return 1
}
return n * factorial(n - 1)
}
factorial(5)
지역변수 전역변수
블록레벨스코프 if, for (안에서 선언한 변수) -> 밖에서 불러서 출력 불가능
밖에서 선언된 x는 함수 내부에서도 접근 가능
함수가 종료된 다음 선언된 변수는 휘발됨
화살표 함수
function 함수1(x,y) {
return x+y;
}
let 함수2 = (x,y) => x+y;
call by value, reference, sharing
javascript는 call by value만 존재합니다.
call by value -> 값의 전달
call by reference -> 참조-주소값의 전달
call by reference처럼 보이지만 주소가 넘어가는 것이 아닌
주소가 복사되어 넘어감
let array = [100, 200, 300];
function test(a) {
a[0] = 1000;
}
test(array)
array
let v = 100;
function test(a) {
a = 1000;
}
test(v)
v
var a = {};
function test(b) {
b = 1000;
}
test(a)
a
클로저
폐쇠된 공간 안의 데이터에 접근
-> 변수 은닉, 메모리 효율, 코드 효율을 극대화하기 위해 사용
function 제곱(x) {
function 승수(y){
return y **x
}
return 승수
}
let 제곱2 = 제곱(2)
제곱2(3)
제곱2(10)
function makeAdder(x) {
var y = 1;
return function(z) {
y = 100;
return x + y + z;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2));
console.log(add10(2));