jongviet

Aug 19, 2021 - array.map, arrow function, array.filter 본문

javascript & typescript

Aug 19, 2021 - array.map, arrow function, array.filter

jongviet 2021. 8. 19. 23:33

*8월19일


*array.map
-forEach와 마찬가지로 array의 각 요소들을 순회하며 callback 함수 실행. callback에서 리턴되는 값을 배열로 만들어냄;
-특정한 배열을 조건에 맞추어 새로운 배열 형태로 반환하되, 기존 배열은 그대로 유지하는 형태;

const oneTwoThree = [1, 2, 3];
let result = oneTwoThree.map((v) => { 
console.log(v);
return v;
});

 

*Arrow function
let result2 = newArr.map(function(v) {
    return v + "i";
});
---->function -> '=>'
let result = newArr.map((v) => {
    return v + "i";
});

----> return까지 축약
let result3 = newArr.map((v) => v * 3);   //param => return
let result4 = newArr.map( (v) => (v * 3) ); // (param) => (return)


*array.filter를 활용한 arrow func & callback
let fArray = newArr.filter( (v) => (v < 3) );
console.log(fArray);


*bind method & arrow function this
-this가 가리키는 값 변경
-setTimeout은 비동기함수로, 이 setTimeout이 실행될 땐 showHealth 함수는 이미 반환이 된 상태이다. 즉, setTimeout안의 this는 window 객체를 가리키게 된다.
->의도한대로 this가 healthObj를 가리키게 하려면 bind 메소드를 사용하면 된다.
->function뒤에 '.bind(this)'로 호출하면 function은 객체로 변하고, function 네이티브 객체에 들어있는 메소드들을 부를 수 있다.

var healthObj = { 
     name : "달리기",
     lastTime : "PM10:12",
     showHealth : function() { 
    setTimeout(function(){ 
        console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");
     }.bind(this), 500);
     } 

healthObj.showHealth();


-arrow function의 경우, 자신을 둘러싼 함수의 this와 같은 값을 가진다. bind를 생략해도 잘 처리됨

var healthObjWithArrow = { 
        name : "달리기", 
        lastTime : "PM10:12", 
        showHealth : function() { 
        setTimeout(()=>{ 
            console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");
         }, 500);
         } 

healthObjWithArrow.showHealth(); //결과 값: 달리기님, 오늘은 PM10:12에 운동을 하셨네요.

    //arrow this context
    const myObj = {
        runTimeout() {
            setTimeout( () => {
                console.log(this === window); //false;
                console.log(this);
                this.printData(); //arrow로 처리했기에, 실행 시 this를 계속해서 유지 중
            }, 2000);
        },
        printData() {
            console.log("hi!");
        }
    }
    myObj.runTimeout();

 

    const el = document.querySelector("p");
    const myObj = {
        register() {
            el.addEventListener("click", (e) => {
                this.printData(e.target); //this는 HTML, 즉 <p> 태그이기에 먹히지 않음
                //.bind(this)를 쓰거나, arrow함수를 쓰면 실행 타이밍에 관계 없이 바로 위의 부모를 this로 잡을 수 있음
            });
        },
        printData(e) {
            console.log("clicked!!", e.innerText);
        }
    }

    myObj.register();

Comments