TypeScript(三) 做一個計算器

TypeScript(三) 做一個計算器

1 人贊了文章

先上一張效果圖

預覽鏈接:

https://yuyunzhi.github.io/typescript-demo/calculator/calc.html?

yuyunzhi.github.io

源碼鏈接:

yuyunzhi/typescript-demo?

github.com圖標

關鍵詞:typescript及ES6中的class,實現了加減乘除功能。

一、知識點

  • TS類型檢查:string、boolean、HTMLDivElement、HTMLSpanElement、Array<Array<string | number>>
  • class語法

class Calculator{//聲明變數 public n1: string = ;constructor(){}//定義方法createContainer(){}}new Calculator() //創建實例

二、代碼邏輯

1、聲明變數

public n1: string = ; public n2: string = ; public result: string = ; public operator: string = ; public equal:boolean=true; public container:HTMLDivElement; public span: HTMLSpanElement; public textLists: Array<Array<string | number>> = [ [c, ÷], [7, 8, 9, ×], [4, 5, 6, -], [1, 2, 3, +], [0, ., =], ];

2、執行代碼包括4個方面

constructor(){ this.createContainer() this.createOutput() this.createButtons() this.bindEvents()}

3、createContainer

createContainer(){ let calc = document.createElement(div); calc.classList.add(calc); document.body.appendChild(calc); this.container = calc; }

4、createOutput

createOutput(){ let output = document.createElement(div); output.classList.add(output); let span = document.createElement(span); output.appendChild(span); span.textContent = 0; this.span = span; this.container.appendChild(output); }

5、createButtons

createButton(text:string|number,container: HTMLElement, className?: string){ let button = document.createElement(button); button.textContent = text.toString(); //className && button.classList.add(className); button.classList.add(className); container.appendChild(button); }

6、bindEvents

bindEvents(){ this.container.addEventListener(click, event => { if (event.target instanceof HTMLButtonElement) { const text = event.target.textContent; if (0123456789..indexOf(text) >= 0) { if (this.operator) { this.n2 += text; this.span.textContent = this.n2; } else { this.result = ; this.n1 += text; this.span.textContent = this.n1; } } else if (+-×÷.indexOf(text) >= 0) { if (this.result) { this.n1 = this.result; this.result = ; } this.operator = text; } else if (=.indexOf(text) >= 0) { if(this.result){ // }else{ this.result = this.removeZero(this.getResult(this.n1, this.n2, this.operator)); console.log(this.result) this.span.textContent = this.result; this.n1 = ; this.n2 = ; this.operator = ; this.equal=false; } } else if (text === c) { this.n1 = ; this.n2 = ; this.operator = ; this.result = ; this.span.textContent = 0; } console.log(this.n1, this.operator, this.n2); } }); }

推薦閱讀:

Vue + TypeScript踩坑(初始化項目)
TypeScript 3.0 元組類型的用法和一些奇技淫巧
ts-node 下錯誤堆棧問題排查小記
TypeScript基礎入門 - 枚舉 - 數字枚舉和...
微軟發起TSDoc項目試圖規範文檔格式

TAG:計算器 | TypeScript | 計算機科學 |