자바스크립트

 

 

 

인프런 수강하기 ==>   자바스크립트 중급 강좌

 

초급자를 위해 준비한
[프로그래밍 언어] 강의입니다.

이 수업은 중급 자바스크립트 수업으로, "자바스크립트 기초 지식이 있으신 분"을 대상으로 진행합니다.

 

강의 목록  :  https://www.youtube.com/playlist?list=PLZKTXPmaJk8JZ2NAC538UzhY_UNqMdZB4

 

 

 

 

 

11 .클로저(Closure) 5분만에 이해하기

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>클로저(Closure) 5분만에 이해하기</title>
</head>
<body>
<script>
function makeAdder(x){
    return function(y){
        return x+y;
    }
}
const add3=makeAdder(3);
console.log("makeAdder(3) : ",makeAdder(3));
//makeAdder(3) :  ƒ (y){return x+y;}
console.log(add3(2));
//5
/******************************
 Closure
 함수와 렉시컬 환경의 조합
 함수가 생성될 당시의 외부 변수를 기억
 생성 이후에도 계속 접근 가능 
 ****************************/

function makeCounter(){
    let num =0; //은닉화
    return function(){
        return num++;
    }
}
let counter=makeCounter();
console.log(counter()); //0
console.log(counter()); //1
console.log(counter()); //2

</script>    
</body>
</html>

 

 

 

 

 

 

12 .setTimeout / setInterval

 

 

  • setTimeout :: 일정 시간이 지난 후에 함수를 실행하는 방법.

  • setInterval :: 일정 시간 간격을 두고 함수를 실행하는 방법.

     

    자바스크립트 명세서엔 setTimeout과 setInterval가 명시되어 있지 않다. 하지만 시중에 나와있는 모든 브라우저, Node.js를 포함한 자바스크립트 호스트 환경 대부분 이와 유사한 메서드와 내부 스케줄러를 지원한다.

 

const timeoutId = setTimeout(() => console.log("5초 후에 실행됨"), 5000);
clearTimeout(timeoutId);

 

setTimeout

문법 ::

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)

 

clearTimeout으로 스케줄링 취소하기

setTimeout을 호출하면 "타이머 식별자(timer identifier)"가 반환된다. 스케줄링을 취소하고 싶을 땐 식별자(아래 예시에서 timerId)를 사용하면 된다.

let timerId = setTImeout(() => alert('아무런 일도 일어나지 않는다.'), 1000);
alert(timerId); // 타이머 식별자

clearTimeout(timerId);
alert(timerId); // 위 타이머 식별자와 동일함.(취소 후에도 식별자의 값은 null이 되지 않는다.)

 

 

setInterval

setInterval 메서드는 setTimeout과 동일한 문법을 사용한다.

let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)

인수 역시 동일하나, setTimeout이 함수를 단 한번만 실행하는 것과 달리, setInterval은 함수를 주기적으로 실행한다.

함수 호출을 중단하려면 clearInterval(timerId)을 사용한다.

 

아래 예제를 실행하면 메세지가 2초 간격으로 보여지다가 5초 이후에는 더 이상 메세지가 보이지 않는다.

// 2초 간격으로 메세지를 보여줌
let timerId = setInterval(() => alert('tick'), 2000);

// 5초 후에 정지
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setTimeout / setInterval</title>
</head>
<body>
<script>
function fn(){
    console.log(3);
}    
setTimeout(fn, 3000);


//setInterval, clearInterval
let num=0;

function showTime(){
    console.log(`안녕하세요. 접속하신지 ${num++}초가 지났습니다.`);
    if(num>5){
        clearInterval(tId);
    }
}
const tId=setInterval(showTime, 1000);


// 안녕하세요. 접속하신지 0초가 지났습니다.
// 안녕하세요. 접속하신지 1초가 지났습니다.
// 3
// 안녕하세요. 접속하신지 2초가 지났습니다.
// 안녕하세요. 접속하신지 3초가 지났습니다.
// 안녕하세요. 접속하신지 4초가 지났습니다.
// 안녕하세요. 접속하신지 5초가 지났습니다.
</script>    
</body>
</html>

 

 

 

 

 

13 .call, apply, bind

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>call, apply, bind</title>
</head>
<body>
<script>

const nums =[3,10,1,6,4];
// const minNum=Math.min(...nums);
// const maxNum=Math.max(...nums);


const minNum=Math.min.apply(null,nums);
//const minNum=Math.min.call(null, ...nums);

//const maxNum=Math.max.apply(null,nums);
const maxNum=Math.max.call(null, ...nums);


console.log(minNum); //1
console.log(maxNum);//10





/**************************************************
 * call
 * call 메서드는 모든 함수에서 사용할 수 있으며, 
 * this를 특정값으로 지정할 수 있습니다.
***************************************************/
const mike={
    name:"Mike",
}    
const tom={
    name:"Tome",
}
function showThisName(){
    console.log(this.name);
}

showThisName();
showThisName.call(mike);
showThisName.call(tom);


function update(birthYear, occupation){
    this.birthYear=birthYear;
    this.occupation=occupation;
}

update.call(mike, 1999, "singer");
console.log(mike);

update.call(tom, 2002, "teacher");
console.log(tom);
// {name: 'Mike', birthYear: 1999, occupation: 'singer'}
// {name: 'Tome', birthYear: 2002, occupation: 'teacher'}




/********************************************************************************************************
 * apply
 * apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같습니다.
 * call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply 는 매개변수를 배열로 받습니다.
*******************************************************************************************************/
update.apply(mike, [1999, "singer"]);
console.log(mike);

update.apply(tom, [2002, "teacher"]);
console.log(tom);
// {name: 'Mike', birthYear: 1999, occupation: 'singer'}
// {name: 'Tome', birthYear: 2002, occupation: 'teacher'}




/********************************************************************************************************
 * bind
 * 함수의 this값을 영구히 바꾸수 있습니다.
*******************************************************************************************************/

const updateMike=update.bind(mike);
updateMike(1960, "police");
console.log("mike  : " ,mike);


const user={
    name:"Mike",
    showName:function(){
        console.log(`hello,${this.name} `);
    }
}
user.showName();
let fn=user.showName;
fn();
// hello,Mike 
// hello, 

//fn() 할당할때 this 잃어 버림

fn.call(user);
fn.apply(user);



let boundFn =fn.bind(user);
console.log("boundFn:==> ");
boundFn();

</script>    
</body>
</html>

 

 

 

 

 

 

14 .상속, 프로토타입(Prototype)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>상속, 프로토타입(Prototype)</title>
</head>
<body>
<script>

const car ={
    wheels:4,
    drive(){
        console.log("drive...");
    }
}

const bmw={
    color:"red",
    navigation:1,
};


const benz={
    color:"black",
};

const audi={
    color:"blue",
};

bmw.__proto__=car;

const x5={
    color:"white",
    name:"x5"
}

x5.__proto__=bmw;


// benz.__proto__=car;
// audi.__proto__=car;

// const car2={
//     wheels:4,
//     drive(){
//         console.log("drive.... ");
//     }
// }

const Bmw2=function(color){
    this.color=color;
}

Bmw2.prototype.wheels=2;
Bmw2.prototype.drive=function(){
      console.log("drive.... ");
}

Bmw2.prototype.navigation=1;
Bmw2.prototype.stop=function(){
    console.log("STOP!");
}

const x6=new Bmw2("red");
const z5=new Bmw2("blue");

// x5.__proto__=car2;
// z4.__proto__=car2;

</script>    
</body>
</html>

 

 

 

 

 

 

 

15.클래스(Class)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>클래스(Class)</title>
</head>
<body>
<script>
//1. 함수 생성자 방식
const User=function(name, age){
    this.name=name;
    this.age=age;
    // this.showName=function(){
    //     console.log(this.name);
    // }
}
User.prototype.showName=function(){
    console.log(this.name);
}
const mike=new User("Mike", 30);



//2.클래스 생성자방식
class User2{
    constructor(name, age){
        this.name=name;
        this.age=age;
    }
    showName() {      
       console.log(this.name);
    }
}

const tom=new User2("Tom", 19);



//클래스 상속 extends
class Car{
    constructor(color){
        this.color=color;
        this.wheels=4;
    }
    drive(){
        console.log("drive...");
    }
    stop(){
        console.log("STOP!");
    }
}

class Bmw extends Car{
    constructor(color){
        super(color);
        this.navigation=1;
    }
    park(){
        console.log("PARK");
    }
    stop(){
        //super.stop(); 오버라이딩
        console.log("OFF");
    }
}


const z4=new Bmw("blue");


</script>    
</body>
</html>

 

 

 

 

16.프로미스(Promise)

 

Promise가 왜 필요한가요?

프로미스는 주로 서버에서 받아온 데이터를 화면에 표시할 때 사용합니다. 일반적으로 웹 애플리케이션을 구현할 때 서버에서 데이터를 요청하고 받아오기 위해 아래와 같은 API를 사용합니다.

$.get('url 주소/products/1', function(response) {
  // ...
});

 

위 API가 실행되면 서버에다가 ‘데이터 하나 보내주세요’ 라는 요청을 보내죠. 그런데 여기서 데이터를 받아오기도 전에 마치 데이터를 다 받아온 것 마냥 화면에 데이터를 표시하려고 하면 오류가 발생하거나 빈 화면이 뜹니다. 이와 같은 문제점을 해결하기 위한 방법 중 하나가 프로미스입니다.

 

프로미스의 3가지 상태(states)

프로미스를 사용할 때 알아야 하는 가장 기본적인 개념이 바로 프로미스의 상태(states)입니다. 여기서 말하는 상태란 프로미스의 처리 과정을 의미합니다. new Promise()로 프로미스를 생성하고 종료될 때까지 3가지 상태를 갖습니다.

  • Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
  • Fulfilled(이행) : 비동기 처리가 완료되어 프로미스가 결과 값을 반환해준 상태
  • Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태

 

 

출처 :https://joshua1988.github.io/web-development/javascript/promise-for-beginners/

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프로미스(Promise)</title>
</head>
<body>
<script>
const pr=new Promise((resolve,reject)=>{
    setTimeout(()=>{
        //resolve("OK");
        reject(new Error("err...."));
    },1000);
})    

pr.then(result=>{
    console.log("result:", result);
}).catch(err=>{
    console.error("에러 :", err);
}).finally(()=>{
    console.log("끝");
})
</script>    
</body>
</html>

 

예2)callback 지옥 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>프로미스(Promise)</title>
</head>
<body>
<script>
//callback    지옥
const f1=(callback)=>{
    setTimeout(function(){
        console.log("1번 주문 완료");
        callback();
    }, 1000);
}   

const f2=(callback)=>{
    setTimeout(function(){
        console.log("2번 주문 완료");
        callback();
    }, 3000);
}   


const f3=(callback)=>{
    setTimeout(function(){
        console.log("3번 주문 완료");
        callback();
    }, 2000);
}   

console.log("시작");
f1(function(){
    f2(function(){
         f3(function(){
            console.log("끝");
        }); 
    });
});



</script>    
</body>
</html>

 

 

 

 

예3) Promiss chaining,    Promise.all  ,  Promise.race

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>프로미스(Promise)</title>
</head>
<body>
<script>
//Promise    
const f1=(message)=>{
    console.log("f1 :", message);
    return new Promise((res, rej)=>{
        setTimeout(function(){
            res("1번 주문 완료");
        }, 1000);
    })
}   

const f2=(message)=>{
    console.log("f2 :", message);
    return new Promise((res, rej)=>{
        setTimeout(function(){
            res("2번 주문 완료");
            // rej("xxx");
        }, 3000);
    })
}   


const f3=(message)=>{
    console.log("f3 :", message);
    return new Promise((res, rej)=>{
        setTimeout(function(){
            res("3번 주문 완료");
        }, 2000);
    })
}    

/**********************************
 * Promise  
 *********************************/
//프로미스 체이닝 (Promiss chaining)
//다음 방식 결과:6~7초
//작동은 느리나 오류 발생시 해당 부분만 건너띄고 실행
console.log("시작");
console.time("시작");
f1()
.then(res=>f2(res))
.then(res=>f3(res))
.then(res=>console.log(res))
.catch(error=>console.error("에러 :", error))
.finally(()=>{
    console.log("끝");
    console.timeEnd("시작");
});
//정상 작동 출력=>
// 시작
// f1 : undefined
// f2 : 1번 주문 완료
// f3 : 2번 주문 완료
// 3번 주문 완료
// 끝




/**********************************
 * Promise.all  배열로 받는다.
 *********************************/
//다음 방식 결과 :3초
//작동 시간은 빠르나 오류발생시 페이지전체 오류발생 - 다보여주거나 아예 안보여 주거나
console.time("x");
Promise.all([f1(), f2(), f3()]).then((res)=>{
    console.log(res);
    console.timeEnd("x");
})
//출력 결과
// f1 : undefined
// f2 : undefined
// f3 : undefined
// (3) ['1번 주문 완료', '2번 주문 완료', '3번 주문 완료']



/**********************************
 * Promise.race  배열로 받는다.
 * all은 모든 작업이 완료될때까지 기다리지만,
 * race 는 말 그대로 경주라 하나라도 완료되면 끝난다.
 *********************************/
console.time("y");
Promise.race([f1(), f2(), f3()]).then((res)=>{
    console.log(res);
    console.timeEnd("y");
})


</script>    
</body>
</html>

 

 

 

 

 

 

 

 

17.async, await

 

 

async와 await

async와 await라는 특별한 문법을 사용하면 프라미스를 좀 더 편하게 사용할 수 있습니다. async, await는 놀라울 정도로 이해하기 쉽고 사용법도 어렵지 않습니다.

 

async 키워드부터 알아봅시다. async는 function 앞에 위치합니다.

async function f() {

 

명시적으로 프라미스를 반환하는 것도 가능한데, 결과는 동일합니다.

async function f() {
  return Promise.resolve(1);
}

f().then(alert); // 1

async가 붙은 함수는 반드시 프라미스를 반환하고, 프라미스가 아닌 것은 프라미스로 감싸 반환합니다. 굉장히 간단하죠? 그런데 async가 제공하는 기능은 이뿐만이 아닙니다. 또 다른 키워드 await는 async 함수 안에서만 동작합니다. await는 아주 멋진 녀석이죠.

 

await 문법은 다음과 같습니다.

// await는 async 함수 안에서만 동작합니다.
let value = await promise;

자바스크립트는 await 키워드를 만나면 프라미스가 처리될 때까지 기다립니다(await는 '기다리다’라는 뜻을 가진 영단어입니다 – 옮긴이). 결과는 그 이후 반환됩니다.

1초 후 이행되는 프라미스를 예시로 사용하여 await가 어떻게 동작하는지 살펴봅시다.

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("완료!"), 1000)
  });

  let result = await promise; // 프라미스가 이행될 때까지 기다림 (*)

  alert(result); // "완료!"
}

f();

함수를 호출하고, 함수 본문이 실행되는 도중에 (*)로 표시한 줄에서 실행이 잠시 '중단’되었다가 프라미스가 처리되면 실행이 재개됩니다. 이때 프라미스 객체의 result 값이 변수 result에 할당됩니다. 따라서 위 예시를 실행하면 1초 뒤에 '완료!'가 출력됩니다.

 

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async, await</title>
</head>
<body>
 <script>
//async 항상 promise 를 반환한다.
async function getNme(){
  // return "Mike";
  //return Promise.resolve("Tom");
  throw new Error("err.");
}
//console.log(getNme());
getNme().then((name)=>{
    console.log(name);
}).catch(err=>{
    console.error("에러 : ", err);
});
 </script>
</body>
</html>

 

 

예2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<script>
/************************
 * aync await
* ***********************/

function getName(name){
    return new Promise((resolve, rej)=>{
        setTimeout(() => {
            resolve(name);
        }, 1000);
    });
}

async function showName(){
    const result=await getName("Mike");
    console.log(result);
}

console.log("시작");
showName();

</script>    
</body>
</html>

 

 

예3)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>프로미스(Promise)</title>
</head>
<body>
<script>
//Promise    
const f1=(message)=>{
    console.log("f1 :", message);
    return new Promise((res, rej)=>{
        setTimeout(function(){
            res("1번 주문 완료");
        }, 1000);
    })
}   

const f2=(message)=>{
    console.log("f2 :", message);
    return new Promise((res, rej)=>{
        setTimeout(function(){
            res("2번 주문 완료");
           //rej("xxx");
        }, 3000);
    })
}   


const f3=(message)=>{
    console.log("f3 :", message);
    return new Promise((res, rej)=>{
        setTimeout(function(){
            res("3번 주문 완료");
        }, 2000);
    })
}    


console.log("시작");
async function order(){
    try{
        // const result1 = await f1();
        // const result2 = await f2(result1);
        // const result3 = await f3(result2);
        // console.log(result3);
        const result=await Promise.all([f1(), f2(), f3()]);
        console.log(result);
    }catch(err){
        console.error(" 에러 : " , err);
    }
    
    console.log("종료");
}

order();

</script>    
</body>
</html>

 

 

 

 

 

 

 

 

18.Generator

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator</title>
</head>
<body>
<script>
/***************************************************
 * Symbol이란?
   Symbol이란 객체에 Unique한 속성을 만들기 위해 사용됩니다.
  왜 Unique가 필요하냐면 다른 라이브러리와의 충돌을 막기 위함입니다.
  Symbol.iterator는 상용심볼로써 이터러블한 객체를 정의하기 위한 심볼입니다.


   iterable (반복 가능한)이란 무엇일까요?
   Symbol.iterator심볼을 속성으로 가지고 있고, iterator 객체를 반환하는 객체를 뜻합니다.

  iterator (반복자)란 무엇일까요?
  iterable 객체가 [Symbol.iterator]() 메소드로 반환하는 이터레이터 객체는 무엇일까요?
   next메소드를 구현하고 있고, done과 value 속성을 가진 객체를 반환하는 객체를 말합니다.
 
 * *************************************************/    
  

 /****************************************************
***************************************************** 
 * Generator
 * 제너레이터는 다른 작업을 하다가 다시 돌아와서
 * next() 해주면 진행이 멈췄던 부분 이어서 실행 
 *
 * ex) Redux Saga
 * 
 * 함수의 실행을 중간에 멈췄다가 재개할 수 있는 기능
 * next(), return(), throw()
 * 
 * iterable
 * -Symbol.iterator 메서드가 있다.
 * -Symbol.iterator 는 iterator 를 반환해야 한다.
 * 
 * iterator
 * - next 메서드를 가진다.
 * - next 메서드는 value 와 done 속성를 가진 객체를 반환한다.
 * - 작업이 끝나면 done 은 true 가 된다.
 * 
 * *************************************************/    
function* fn(){
    try {
        console.log(1);
        yield 1;
        console.log(2);
        yield 2;
        console.log(3);
        console.log(4);
        yield 3;
        return "finish";        
    } catch (error) {
        console.error("에러 :", error);
    }

}    
const a =fn();

//실행  가장 가까운 yield 문을 만날때까지 실행
//a.next();
console.log(a.next());
//{value: 1, done: false}




</script>    
</body>
</html>

 

 

예2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator</title>
</head>
<body>
<script>
/**************************************************** 
 * Generator
 * 
 * 숫자를 입력 받아 계산 처리 할 수 있다.
 * *************************************************/ 
function* fn(){
    const num1=yield "첫번째 숫자를 입력해주세요.";
    console.log(num1);

    const num2=yield "두번째 숫자를 입력해주세요.";
    console.log(num2);

    return num1+num2;
}    
const a=fn();
</script>    
</body>
</html>

 

예3)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator</title>
</head>
<body>
<script>
/**************************************************** 
 * Generator
* 값을 미리 만들어 두지 않음.
 * *************************************************/ 
function* fn(){
   let index=0;
   while(true){
        yield index++;
   }
}    
const a=fn();
</script>  
</body>
</html>

 

예4)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator</title>
</head>
<body>
<script>
/**************************************************** 
 * Generator
* yield* 을 이용
 * *************************************************/ 
function* gen1(){
    yield "W";
    yield "o";
    yield "r";
    yield "l";
    yield "d";
}
function* gen2(){
    yield "Hello,";
    yield* gen1();
    yield "!";
}
</script>    
</body>
</html>

 

 

 

 

 

 

19.ES2021 자바스크립트에 추가된 새로운 기능들을 알아보자!

 

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ES2021 자바스크립트에 추가된 새로운 기능들을 알아보자!</title>
</head>
<body>
<script>
/*******************************
 String.replaceAll
*******************************/

const str1 ="Hello World";
//console.log(str1.replace(/l/g,"~"));
console.log(str1.replaceAll("l","~"));

const str2="I'm  [Mike]. This is Tom's [Car].";
console.log(str2.replaceAll("[","~").replaceAll("]","~") );
console.log(str2.replace(/\[/g,"~").replace(/\]/g,"~") );
</script> 
</body>
</html>

 

 

예2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ES2021 자바스크립트에 추가된 새로운 기능들을 알아보자!</title>
</head>
<body>
<script>
/*******************************
 * 
 Promise.any 추가됨

Promise.race:
:프로미스중에 가장 먼저 완료된 결과값으로 이행/거부


Promise.any 
:프로미스 중에 가장 먼저 이행된 객체 반환
*******************************/

const rejPromise=new Promise((res, rej)=>{
    setTimeout(()=>{
        rej("fail....");
    },1000);
});

const resPromise=new Promise((res, rej)=>{
    setTimeout(()=>{
        res("sucdess");
    }, 2000);
});


Promise.race([rejPromise, resPromise])
.then(()=>console.log("race 성공"))
.catch(error=>console.error("에러:",error));


Promise.any([rejPromise, resPromise])
.then(()=>console.log("any 성공"))
.catch(error=>console.error("에러:",error));

//Promise.any 모두 거부시 다음과 같은 에러
//에러: AggregateError: All promises were rejected

</script> 
</body>
</html>

 

 

예3)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ES2021 자바스크립트에 추가된 새로운 기능들을 알아보자!</title>
</head>
<body>
<script>
function add1(num1, num2){    
    console.log(num1 +num2);
}
add1(1);
//NaN

function add2(um1, num2){
    num1 ||=0;
    num2 ||=0;
    console.log(num1 +num2);
}
add2(1);
//출력 
//1

/*******************************
|| : 앞의 값이 falsy 이면 뒤의 값
??: 앞의 값이 null 이나 undefined 이면 뒤의 값
*******************************/
let num =0;
let a =num || 3;
//a
//3


let b=num ?? 3;
//b
//0  =>num 인 0이 찍힘
//null undefined


/*******************************
숫자 단위 _ 사용가능 가독성 효과
*******************************/
let billion=1_000_000_000


</script> 
</body>
</html>

 

 

 

소스 :  https://github.com/braverokmc79/Intermediate-javaScript-1

 

 

 

 

about author

PHRASE

Level 60  라이트

교육의 목적은 인격의 형성에 있다. 교육의 목적은 기계적인 사람을 만드는 데 있지 않고, 인간적인 사람을 만드는 데 있다. 또한 교육의 비결은 상호존중의 묘미를 알게 하는데 있다. 일정한 틀에 짜여진 교육은 유익하지 못하다. 창조적인 표현과 지식에 대한 기쁨을 깨우쳐주는 것이 교육자 최고의 기술이다. -아인슈타인

댓글 ( 4)

댓글 남기기

작성