【问题标题】:Javascript calculator how to allow multiple dotsJavascript计算器如何允许多个点
【发布时间】:2021-08-16 18:26:38
【问题描述】:

所以基本上这个项目差不多完成了。但是当我“测试”它时,我发现我无法创建多个点。我知道为什么我不能这样做:

// if there is any dot, and user want to add another dot, then return
    if(containDot && operand == '.') return;

所以,问题是我没有其他想法,如何阻止在 ONE 数字上添加多个点,同时允许将其添加到另一个数字中,以便使用 eval 进行操作();

代码链接如下: https://codepen.io/Igor34/pen/LYyoZMR

【问题讨论】:

  • 可以使用正则表达式:if (/\..*\./.test(input))
  • 为什么需要多个点?如果您保留每个条目的列表(由运算符分隔的数字(,您可以确保每个条目最多有 1 个点。

标签: javascript calculator


【解决方案1】:

我修改了您的代码,将文本拆分为每个数字,并仅在最后一个数字上查找点。

const currentOperator = this.currentScreen.textContent.split(/[-+\\/\\*]/).pop();
// if there is any dot, and user want to add another dot, then return
if (currentOperator.includes(".") && operand === ".") return

// LINE BELOW REMOVED
// if(containDot && operand == '.') return;

https://codepen.io/jmendes/pen/XWRwjJm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多