スマホの電卓にある計算履歴とその計算時刻を表示する機能を追加しまいた
成果
実装内容の説明
履歴とその時刻を格納する配列を作ります
cal_historys: [],
この中に,=または,特殊文字が押された時に格納していきます. 可能時に配列を生成し,その中に式と答え,時刻を入れます
this.cal_historys.push(new Array(this.formula + "=" + this.ans, new Date()));
コード
html(抜粋)
<table class="ui table"> <thead> <tr> <th>履歴</th> <th>時刻</th> </tr> </thead> <tbody v-for="item in cal_historys"> <tr> <td>{{item[0]}}</td> <td>{{item[1]}}</td> </tr> </tbody> </table>
javascript(Vue.js)
var app = new Vue({ el: '#app', data: { ans: '', formula: '', now: new Date(), cal_historys: [], buttons: [ [7, 8, 9, '-', '', '√'], [4, 5, 6, '/', '', 'x^2'], [1, 2, 3, '*', '', 'log'], [0, '00', '+', '=', '', 'sin'] ], }, computed: { response: function () { return this.ans ? eval(this.formula) : ""; } }, methods: { calc: function (cmd) { if (cmd === '=') { this.ans = eval(this.formula); this.cal_historys.push(new Array(this.formula + "=" + this.ans, new Date())); } else if (cmd === 'C') { this.ans = 0; this.formula = 0; } else if (cmd === '√') { this.ans = Math.sqrt(eval(this.formula)); this.push_history("√" + this.formula + "=" + this.ans, new Date()); } else if (cmd === 'x^2') { this.ans = Math.pow(this.formula, 2); this.push_history(this.formula + "^2 "+ "=" + this.ans, new Date()); } else if (cmd === 'log') { this.ans = Math.log(eval(this.formula)); this.push_history("log"+this.formula + "=" + this.ans, new Date()); } else if (cmd === 'sin') { this.ans = Math.sin(eval(this.formula) / 180 * Math.PI); this.push_history("sin(" + this.formula +")"+ "=" + this.ans, new Date()); } else { this.formula += cmd; } } } });