function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers)//sum이라는 함수에 배열 numbers의 원소들을 인자로 전달.
//배열 합치기
let parts = ['eyes', 'nose', 'mouth'];
let face = ['hair', ...parts, 'and', 'ears']
//배열 복사
let arr = [1, 2, 3];
let arr2 = [...arr];
arr2.push(4) // spread 문법은 immutable이므로 arr는 수정되지 않음.
//객체에서 spread문법 사용
let obj1 = { name: '까치', age: 6 };
let obj2 = { name: '삼순', char: 'bad'};
let copydog = {...obj1}
let animals = {...obj1, ...boj2};// 겹치는 키 name에는 '삼순'이 키 값으로 담긴다.
function sum (...theArgs){
let total = 0;
for(const arg of theArgs){
total += arg;
}
return total;
}
console.log(sum(1,2,3))//6
console.log(sum(1,2,3,4))//10
function myFun(a,b, ...manyMoreArgs) {
console.log("a",a);
console.log("b",b);
console.log("manyMoreArgs", manyMoreArgs);
myFun("one","two","three","four","five","six")
// 콘솔 출력은 아래와 같음.
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]
(https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 js 표현식.
spread 문법을 이용해 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정.
객체에서 구조 분해 할당 사용하는 경우, 선언(const, let, var)과 함께 사용하지 않으면 에러 발생할 수 있음.
let a, b, rest;
[a, b] = [10, 20];
console.log(a)// 10
console.log(b)// 20
[a,b, ...rest] = [10,20,30,40,50];
console.log(rest)// [30,40,50]
({a, b} = { a:10, b:20 });
console.log(a) //10
console.log(b) //20
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
구조 분해 할당은 객체, 배열을 할당해주는 표현방식 (ex: var x = [1,2,3,4,5]) 과 비슷하지만, 대신 아래와 같이 할당문의 좌변에서 사용하여 원래 변수에서 어떤 값을 분해해 할당할 지를 정의함.
var x = [1,2,3,4,5];
var [y,z] = x;
console.log(y) //1
console.log(z) //2
lexical scope(정적 스코프) : 자바스크립트 엔진은 함수를 호출한 위치가 아니라 함수가 정의된 위치에 따라 상위 스코프를 결정한다.
const x = 1;
function foo() {
const x = 10;
bar();
}
function bar(){
console.log(x);
}
bar();//1
foo();//1
// foo 속에 x가 10이라고 해도, bar 함수가 선언된 곳은 x가 1로 할당되었기 때문에, 1을 출력함.
Outer 함수 내부에 있는 변수 x에 함수 밖에서 접근하는 방법?
const x = 1;
function outer(){
const x = 10;
}
console.log(x);// x=1
function outer(){
const x = 10;
const inner = function (){
console.log(x)
}
return inner
}
const innerFunc = outer()
innerFunc()//콘솔창에 10 출력.
return function () {
box.style.display = isShow ? 'block' : 'none';
isShow = !isShow;
};
마지막 문제에서 클로저를 사용한 이유는 클로저를 사용하지 않으면 전역변수를 만들게 되기 때문이라고 한다. 전역 변수를 만들게 되면 프로젝트 규모가 커졌을 때, 만든 전역 변수를 의도치 않게 건드리게 될 수 있기 때문이다.
함수 뒤에 ()를 붙이면 '즉시 실행 함수'인데, 함수를 실행해서 나온 값을 변수에 넣는 것.
토글 누를 때마다 내부함수가 실행될 것! (외부함수가 리턴한 것이 내부함수이므로 내부함수가 실행됨)
display : none (안 보임), display : block (다시 보임)
삼항 연산자 : isShow ? block : none
=> isShow가 true면 block, false면 none을 반환.
isShow = isShow!를 해주는 이유 : 다음에 실행할 때 반대로 작동하기 위함!
Math.max() 함수는 인자가 숫자로 전달이 되어야 함. 배열이 전달되면 NaN이 뜬다!!!
js의 + 연산자는 문자의 연결 & 숫자를 더하는 기능을 가지고 있어서 값의 형식을 검사해서 문자열이나 숫자로 변환하는데, - 연산자는 숫자의 뺄셈을 담당하는 기능이라 평가하는 값의 형식을 검사 없이 숫자로 변환하여 계산함. (그래서 1 + "1" 은 "11"이 나오는데 "123" - 1 을 하면 122가 나옴.)
js에서 true는 숫자 1과 같고, false는 0과 같음.