【发布时间】:2021-12-16 05:30:57
【问题描述】:
我使用 Javascript 构建了一个简单的计算器,但是当我进行诸如 012 + 3 之类的操作时,它总是返回 13 而不是 15...!
此外,在我的计算器中,当我将任何数字除以 0 时,它会返回“Infinity”,但我想将“Error”或“It is not calculable”作为字符串返回。在这种情况下我该怎么办?
我花了很多时间在 StackOverflow 中搜索解决方案,因为我注意到这个问题非常频繁,但我没有找到真正适合我的代码的解决方案。
这是我的代码:
let output = document.getElementById('output');
let cells = Array.from(document.getElementsByClassName('cell'));
// console.log(cells);
cells.map(cell => {
cell.addEventListener('click', (e) => {
/* console.log('clicked');
console.log(e);
console.log(e.target);
console.log(e.target.innerText); */
switch (e.target.innerText) {
case 'C':
output.innerText = '';
break;
case '=':
// Funzione di gestione degli errori;
try {
output.innerText = eval(output.innerText);
} catch {
output.innerText = 'Error!';
}
break;
default:
output.innerText += e.target.innerText;
}
});
});
<div>
<div class="calculator">
<div id="output"></div>
<div class="buttons">
<button class="cell operator">+</button>
<button class="cell operator">*</button>
<button class="cell operator">/</button>
<button class="cell operator">-</button>
<button class="cell">7</button>
<button class="cell">8</button>
<button class="cell">9</button>
<button class="cell">4</button>
<button class="cell">5</button>
<button class="cell">6</button>
<button class="cell">1</button>
<button class="cell">2</button>
<button class="cell">3</button>
<button class="cell">0</button>
<button class="cell">.</button>
<button class="cell">C</button>
<button class="cell result">=</button>
</div>
</div>
</div>
【问题讨论】:
-
0 表示前缀为八进制,10 + 3 = 13。
-
只检查结果is finite。
-
我认为不建议使用
eval,因为它会产生一些安全问题 -
我会避免使用 eval,只要这是一个在内部网络上运行的封闭项目...stackoverflow.com/questions/197769/… 和 stackoverflow.com/questions/86513/…
标签: javascript html css ecmascript-6