상세 컨텐츠

본문 제목

[자바스크립트] 수업에서한거 5.22

카테고리 없음

by esoesmio 2023. 5. 22. 22:28

본문

const a = [1,2,3,4,5];
가 있는데 reduce로 sum, max 만들어라
 
const a = [1,2,3,4,5];


const max = a.reduce((x,y)=>x>y?x:y);
console.log(max);


const sum = a.reduce((x,y)=>(x+y));
console.log(sum);

 

const a = [
{
id:4,name:'장길산',year:4,result:5.1
},
{
id:6,name:'1장길산',year:7,result:1.1
},
{
id:1,name:'2장길산',year:4,result:5.1
}

]

 

여기서 체이닝 해봐라. 필터 포이치

 

const a = [
    {
        id:4,name:'장길산',year:4,result:5.1
    },
    {
        id:6,name:'1장길산',year:7,result:1.1
    },
    {
        id:1,name:'2장길산',year:4,result:5.1
    }

]

z = a.filter(k=>k.id===1)
.forEach(b=>console.log(b))

 

const a = [
    {
        id:4,name:'장길산',year:4,result:5.1
    },
    {
        id:6,name:'1장길산',year:7,result:1.1
    },
    {
        id:1,name:'2장길산',year:4,result:5.1
    }

]

a.forEach(

    a=>{
        if(a.result>2){
            console.log('잘햇네요');
        }else{
            console.log('못했네요');
        }


    }


)

 

기본파라미터있는거, a가 있으면 a고 없으면 10이고 b도있고 그거 해봐라

 

 

const add = (a=10, b=20)=>{
    return a+b;
}

console.log(add());

console.log(add(30,40));

const add2 = (a,b)=>{
    //단축평가를 이용한 파라미터 기본값 지정

    this.a = a || 10;
    this.b = b || 20;
console.log(this.a);
console.log(b);

}

add2(null,null);

console.log(this.a);

 

rest 파라미터. ...rest하면 걍 파라미터 몇개 가져와도  ...rest 하나의 괄호안에 다 쓸수 있다. 근데 rest는 이터레이터블이라서 for안에 나열할수도 있다.

 

const add = (...rest)=>{
console.log(rest);
    let sum=0;
    for(let i=0;i<rest.length;i++){
        sum+=rest[i];
    }
    console.log(sum);
}
add(1,2,3,4);
console.log('여기까지');
//파라미터중 원하는 개수만 변수로 받고 나머지는 restparameter로 받기
const mul = (num1, num2, ...rest)=>{
    let result=1;
    console.log(num1);
    console.log(num2);
    console.log(rest);
    for(let i=0;i<rest.length;i++){
        result*=rest[i];
    }

    console.log(result);

}

mul(3,4,7,10);

 

버튼 누를때마다 누른횟수 n 이렇게 바뀌는거

 

 

<!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>Title</title>
    <style>

    </style>
</head>
<body>

<button type="button">버튼</button>

</body>

<script>
let cnt = 0;
const btn = document.querySelector('button');
btn.addEventListener('click',()=>{
    btn.innerText = `클릭횟수 : ${++cnt}`

})

// btn.addEventListener('click',function(e){
//     console.log(e);
//     this.innerText =`클릭횟수 : ${++cnt}`
//
// })

btn.addEventListener('click',(e)=>{
    console.log(e);

    e.target.innerText =`클릭횟수 : ${++cnt}`

})

</script>
</html>

 

 

 

화살표함수 만드는 방법

 

 

function add1(a,b){
    return a+b;
}

const add2 = (a,b)=>{
    return a+b;
}
const add3 = (a,b)=>(
    a+b
);
//매개변수가 하나일 때는 소괄호 생략 하능
const returnfunc1 = a=>{
    return a*100;
}
// 리턴될 대상이 연산이 필요없는 대상일 경우 소괄호 생략 가능
const returnfunc2 = a=>a*300;
console.log(10,20);
console.log(returnfunc2(100));
console.log(returnfunc1(100));

 

 

클래스의 상속

 

 

function parent(height, haircolor){
    this.height = height;
    this.haircolor = haircolor;

}


class child extends  parent{
    constructor(weight, ...args){
        super(...args);
        this.weight = weight;
    }

}


const child2 = new child(80, 192, 'red');
console.log(child2);

 

축약표현

 

 

var kiacar = {
    price : 100000,
    color : 'red',
    company : 'kia'
};
console.log(kiacar);
let price = 2000000;
let color = 'black';
let company = 'hyundai';

const hyundaicar = {price, color, company};
console.log(hyundaicar);
///축약표현

var colorobj1 = {}
var cnt1 = 0;

colorobj1['색상'+(++cnt1)]='red';
colorobj1['색상'+(++cnt1)]='red';
colorobj1['색상'+(++cnt1)]='red';
colorobj1[`색상${++cnt1}`]='gold'
//es6 계산된 속성 이름
//템플릿 리터럴의 표현식 삽입 기능을 이용한 동적 속성키 배정
console.log(colorobj1);

let cnt2 = 0;
const colorobj2 = {
    ['색상'+(++cnt1)]:'red',
    ['색상'+(++cnt1)]:'blue',
    ['색상'+(++cnt1)]:'gold',

}
console.log(colorobj2);

 

 

 

 

 

축약논리. 없으면 뭘 뽑아내라!

 

 

 

 

 

const objarr = [
    {
        num:1
    },{
    num:2
    },
    {
        num:5
    }
];
console.log(objarr[2]||"해당데이터가 존재하지 안흔ㄴ다");

for(let i=0;i<objarr.length;i++){

    console.log(  objarr[i]&&objarr[i].num         );
}

 

 

 

축약논리 상자 변경, 원복

 

 

 

<!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>Title</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
<div class="box"></div>
<button type="button">버튼</button>

</body>

<script>
    let isclicked = true;
    const btn = document.querySelector("button");
    const box = document.querySelector(".box")
let message = isclicked&&'성공';
  alert(message)
    btn.addEventListener('click', () => {
        if (isclicked) {
            box.style.background = 'blue'
            let message2 = isclicked&&'변경';
            alert(message2);
        } else {
            box.style.background = 'red'
            let message3 = isclicked||'원복';
            alert(message3);

        }
        isclicked = !isclicked;
    })


</script>
</html>

 

 

 

 

댓글 영역