简体   繁体   English

在JavaScript计算器中将NaN更改为Error

[英]Change NaN to Error in JavaScript calculator

I have a JavaScript calculator which has numerous functions defined as follows (using ln as an example): 我有一个JavaScript计算器,它具有定义如下的许多功能(以ln为例):

function ln(form) {
  form.display.value = Math.log(form.display.value);
}

If the user inputs a negative number and clicks the button to activate this function, it returns NaN since ln is undefined for negative values. 如果用户输入一个负数并单击该按钮以激活此功能,则由于未定义ln为负值,因此它将返回NaN I would like for it to return Error however. 我希望它返回Error I have tried this, but it causes the script to stop working: 我已经尝试过了,但是它导致脚本停止工作:

var displayValue = form.display.value;
if (isNaN(displayValue)) displayValue = 'Error';

Here is the HTML markup of the display if required: 如果需要,这是显示的HTML标记:

<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>

How might I get this to return the desired output? 我如何获得返回期望的输出?

Try something like this: 尝试这样的事情:

function ln(form) {
    if(isNan(Math.log(form.display.value))){
       form.display.value = 'Error';
    } else {
      form.display.value = Math.log(form.display.value);
    } 
  }

The value returned from form.display.value is a String. form.display.value返回的值是一个字符串。 This means that isNaN will always return true if the value cannot be parsed into a Number . 这意味着,如果无法将值解析为Number ,则isNaN将始终返回true You need to change this value to a Number first: 您需要首先将此值更改为Number

function ln(form) {
  var displayValue = parseFloat(form.display.value);

  if(isNaN(displayValue)){
    form.display.setAttribute('value', 'Error');
  } else {
    form.display.setAttribute('value', Math.log(displayValue));
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM