指定值“.” 无法解析或超出范围

Eri*_*ick 4 javascript dom

我试图制作一个计算器,但我遇到了“点”的问题,因为给我这样的广告......

“指定的值‘.’无法解析,或者超出范围。”

这是我的代码...

numberDot.addEventListener('click', function() {
    numberDot = '.' ;
    input.value = input.value + numberDot;
    console.log(typeof(input.value));
    console.log(input.value);
});
Run Code Online (Sandbox Code Playgroud)

use*_*349 5

这是一种方法

使用type="number"输入和单选按钮来选择操作。这有助于人们输入数字。您还可以使用type="text"

重要的部分是将字符串数据转换为数值

当您从输入的 value 属性读取数据时,数据将以字符串形式返回。parseInt可以使用(对于整数)或parseFloat(对于浮点数)将其转换为数字。如果无法解析,NaN则返回 (Not a Number)。要测试NaN,请使用isNaN().

例如:

let x = "kittens";
let n = parseInt(x);
if (isNaN(n)) {
    console.log(x + " is not a number");
}
Run Code Online (Sandbox Code Playgroud)

该示例的重要部分是数字的转换并确定要执行的操作。

let x = "kittens";
let n = parseInt(x);
if (isNaN(n)) {
    console.log(x + " is not a number");
}
Run Code Online (Sandbox Code Playgroud)
// get the elements in the DOM
let numberOne = document.getElementById("numberOne");
let numberTwo = document.getElementById("numberTwo");
let output = document.getElementById("output");
let calculator = document.getElementById("calculator");

// every time the calculator values change
calculator.addEventListener('change', function(evt) {

  // get the values from the number inputs and try to convert them to floating point
  let valueOne = parseFloat(numberOne.value);
  let valueTwo = parseFloat(numberTwo.value);

  // if both numbers are numbers (this is not 100% accurate)
  if (!isNaN(valueOne) && !isNaN(valueTwo)) {
  
    // create a variable to store the result
    let value = 0;
    
    // get the radio buttons
    let ops = calculator['operation'];
    
    // use the selected radio button to determine the operation
    switch (ops.value) {
      case '+':
        value = valueOne + valueTwo;
        break;
      case '-':
        value = valueOne - valueTwo;
    }
    
    // display the result
    output.textContent = value;
  }
});
Run Code Online (Sandbox Code Playgroud)