꿈꾸는 새벽하늘

[노마드코더] JavaScript (2) 본문

💻 Programming

[노마드코더] JavaScript (2)

rovemin 2022. 6. 23. 05:58

1. 함수를 활용해서 calculator 객체 만들기

const calculator = {
    plus: function(num1, num2) {
        console.log(num1 + " + " + num2 + " : " + (num1 + num2));
    },
    minus: function(num1, num2) {
        console.log(num1 + " - " + num2 + " : " + (num1 - num2));
    },
    times: function(num1, num2) {
        console.log(num1 + " * " + num2 + " : " + (num1 * num2));
    },
    divide: function(num1, num2) {
        console.log(num1 + " / " + num2 + " : " + (num1 / num2));
    },
    power: function(num1, num2) {
        console.log(num1 + " ** " + num2 + " : " + (num1 ** num2));
    }
};

calculator.plus(10, 5);     //10 + 5 : 15
calculator.minus(30, 10);   //30 - 10 : 20
calculator.times(3, 4);  //3 * 4 : 12
calculator.divide(36, 6);   //36 / 6 : 6
calculator.power(2, 3);     //2 ** 3 : 8

 

2. return문으로 calculator 객체 만들기

const calculator = {
    plus: function(num1, num2) {
        return num1 + num2;
    },
    minus: function(num1, num2) {
        return num1 - num2;
    },
    times: function(num1, num2) {
        return num1 * num2;
    },
    divide: function(num1, num2) {
        return num1 / num2;
    },
    power: function(num1, num2) {
        return num1 ** num2;
    }
};

const plusResult = calculator.plus(10, 5);
const minusResult = calculator.minus(plusResult, 11);
const timesResult = calculator.times(minusResult, 5);
const divideResult = calculator.divide(timesResult, 2);
const powerResult = calculator.power(divideResult, 2);

console.log(plusResult);    //15
console.log(minusResult);   //4
console.log(timesResult);   //20
console.log(divideResult);  //10
console.log(powerResult);   //100

 

3. parseInt()

parseInt()는 문자열을 숫자로 바꿀 때 사용한다.

const year = "2022";

console.log(typeof year);           //string
console.log(typeof parseInt(year)); //number

 

4. NaN(Not-a-Number)

isNaN()을 통해 NaN 여부를 판단할 수 있다.

isNaN()은 인수가 NaN이면(즉, 숫자가 아니면) true를 반환하고, NaN이 아니면(즉, 숫자이면) false를 반환한다.

const name = "user";
const year = 2022;

console.log(isNaN(name));   //true
console.log(isNaN(year));   //false

 

5. If문

const score = parseInt(prompt("What is your Math score?"));

if (isNaN(score) || score < 0 || score > 100) {
    console.log("Write your correct score.");
} else if (score >= 90) {
    console.log("Your grade is A.");
} else if (score >= 80) {
    console.log("Your grade is B.");
} else if (score >= 70) {
    console.log("Your grade is C.");
} else if (score >= 60) {
    console.log("Your grade is D.");
} else if (score < 60) {
    console.log("Your grade is F.");
}

 

'💻 Programming' 카테고리의 다른 글

[노마드코더] JavaScript (4)  (0) 2022.06.29
[노마드코더] JavaScript (3)  (0) 2022.06.28
[노마드코더] JavaScript (1)  (0) 2022.06.23
[생활코딩-WEB2] CSS (2)  (0) 2022.06.21
[생활코딩-WEB2] CSS (1)  (0) 2022.05.04