试图从提示中解析整数

时间:2017-10-17 01:54:07

标签: javascript parsing integer parseint

我正在尝试解析两个提示中的整数(将采用字符串)并将两个答案一起添加。到目前为止,提示工作正常,但文档中没有像预期的那样写入任何内容。你能告诉我为什么我的代码没有正确显示吗?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Chapter 2, Example 6</title>
  </head>
  <body>
    <script>
var firstNumber = prompt("Enter the first number");
var secondNumber = prompt("Enter the second number");

  var theTotal = firstNumber.parseInt() + secondNumber.parseInt();
  document.write(firstNumber + "added to " + secondNumber + " equals"  + theTotal);

    </script>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

window.prompt()返回一个字符串。

parseInt()不是String prototype的方法,而是接受要解析的字符串的内置函数。

更新此行:

var theTotal = firstNumber.parseInt() + secondNumber.parseInt();

致:

var theTotal = parseInt(firstNumber) + parseInt(secondNumber);

另外,为避免读者混淆并保证可预测的行为,请传递第二个参数(即radix) - 大概是10个基数为10的数字。

var theTotal = parseInt(firstNumber, 10) + parseInt(secondNumber, 10);

&#13;
&#13;
var firstNumber = prompt("Enter the first number");
var secondNumber = prompt("Enter the second number");

var theTotal = parseInt(firstNumber, 10) + parseInt(secondNumber, 10);
console.log(firstNumber + " added to " + secondNumber + " equals: "  + theTotal);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

运行代码时,必须显示 firstNumber.parseInt不是函数 secondNumber.parseInt不是函数,因为我们使用parseInt()函数将strings格式转换为integer格式,使其类似于parstInt(firstNumber)。在添加 firstNumber secondNumber 之前,请检查prompt值,否则它将返回NaN

  <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Chapter 2, Example 6</title>
  </head>
  <body>
<script>

var firstNumber = prompt("Enter the first number","");
var secondNumber = prompt("Enter the second number","");
if (firstNumber == "" || secondNumber == "") {
   var firstNumber = prompt("Enter the first number","");
   var secondNumber = prompt("Enter the second number","");
}else{
   var theTotal = parseInt(firstNumber, 10) + parseInt(secondNumber, 10);
document.write(firstNumber + " added to " + secondNumber + " equals "  + theTotal);
}
</script>
  </body>
</html>