Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Far from it.

계산기 만들기 본문

JS

계산기 만들기

두유콩 2020. 4. 22. 14:13

https://ko.javascript.info/task/calculator

 

계산기 만들기

let calculator = { sum() { return this.a + this.b; }, mul() { return this.a * this.b; }, read() { this.a = +prompt('첫 번째 값:', 0); this.b = +prompt('두 번째 값:', 0); } }; calculator.read(); alert( calculator.sum() ); alert( calculator.mul() ); 샌드박스를 열어 정답을 확인해

ko.javascript.info

내가 작성한 답안

<script>

  let calculator  = {

    num1 : 0,
    num2 : 0,
    read(){
      this.num1 = prompt("첫번째 숫자를 입력하세요")
      this.num2 = prompt("두번째 숫자를 입력하세요")
    },
    sum(){
      return Number(this.num1) + Number(this.num2);
    },
    mul(){
      return this.num1*this.num2;
    }

  }

  calculator .read();
  alert(calculator .sum())
  alert(calculator .mul())

</script>

 

해답

let calculator = {
  sum() {
    return this.a + this.b;
  },

  mul() {
    return this.a * this.b;
  },

  read() {
    this.a = +prompt('첫 번째 값:', 0);
    this.b = +prompt('두 번째 값:', 0);
  }
};

calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );

 

객체에 프로퍼티를 추가하려면 object.property 형식으로 써주면 되는데, 나는 미리 객체에 선언하여 계산.

 

그리고 prompt로 받으면 string이여서 곱셈은 제대로 작동 되지만 덧셈은 연산이 안되어 Number로 해주어야 하는 것으로 알고 있었는데 그럴 필요가 없는 모양이다. 라고 생각했지만 Number 빼니 계산이 되지 않았음.

 

자세히 보니 prompt() 앞에 +가 붙어있는게 확인되었고, Number를 빼고 +를 붙여넣으니 제대로 연산되는 것을 확인했다.

 

아마도 +를 붙이면 내부적으로 Number가 호출되는게 아닌가 싶다.

 

 

 

'JS' 카테고리의 다른 글

Animate.css  (0) 2020.04.22
객체 리터럴에서 'this' 사용하기  (0) 2020.04.22