JS将字符转换为整数然后添加它们

时间:2018-02-03 19:07:01

标签: javascript html

我试图将字符转换为整数然后添加它们。我有一个JS输入标记来接受文本,然后使用parse int将其转换为整数。不幸的是,当我输入值a时,它会返回NaN,这是唯一的一个。现在宣布了。这是我的代码

<!DOCTYPE HTML>
<html>

<head>
</head>

<body>
   <center>
    <div class="">

     Enter the first number: <input type="text" id="txt1" ><br > 

     Enter the seccond number: <input type="text" id="txt2" ><br > 

     Enter the third number: <input type="text" id="txt3" ><br >

     Enter the fourth number: <input type="text" id="txt4" ><br > 

     Enter the fifth number: <input type="text" id="txt5" ><br >

     Enter the sixth number: <input type="text" id="txt6" ><br >
    </div>
  </center>



  <center><input type="button" onclick="call()" value="Add" > 
  </center> 

  <p id="output"> "Grade 1"</p>

  <script>

    var a = parseInt("4")

    function call() {
        var y = parseInt(document.getElementById("txt1").value);
        var yy = parseInt(document.getElementById("txt2").value);
        var yyy = parseInt(document.getElementById("txt3").value);
        var yyyy = parseInt(document.getElementById("txt4").value);
        var yyyyy = parseInt(document.getElementById("txt5").value);
        var yyyyyy = parseInt(document.getElementById("txt6").value);

        var result = (y + yy + yyy + yyyy + yyyyy + yyyyyy) / 6 ;


        document.getElementById("output").innerHTML = result;
    }

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

3 个答案:

答案 0 :(得分:1)

您无法解析数字中的整数。在这种情况下,parseInt()正在做的事情正是如此,因为a N ot A N umber。

但是,如果您设置了一组简单的键/值对,则可以将字母等级映射到相应的数字。

此外,在JavaScript中执行所有事件处理。不要将内联HTML事件属性(onclick等)用作 there are many reasons ,不要使用这种古老的(25岁)技术。

// We will store the possible grades in a simple object for key/value mapping
var grades = {
  a:4,
  b:3,
  c:2,
  d:1
}

// Get all the input elements into an array
var inputs = Array.prototype.slice.call(document.querySelectorAll("input[type=text]"));

// Get a reference to the button
var btn = document.querySelector("input[type=button]");

// Set up your event handler in JavaScript, not in HTML
btn.addEventListener("click", function() {
  var sum = 0;
  // Loop over the inputs
  inputs.forEach(function(input){
     sum += grades[input.value.toLowerCase()] || 0;  
  });
  // As long as there is a sum, go ahead and divide it.
  document.getElementById("output").textContent = sum / 6;
});
<div class="">
  Enter the first grade: <input type="text" id="txt1"><br> 
  Enter the seccond grade: <input type="text" id="txt2"><br> 
  Enter the third grade: <input type="text" id="txt3"><br>
  Enter the fourth grade: <input type="text" id="txt4"><br> 
  Enter the fifth grade: <input type="text" id="txt5"><br>
  Enter the sixth grade: <input type="text" id="txt6"><br>
</div>
<input type="button" value="Add">
<p id="output">"Grade 1"</p>

现在,您仍然会遇到此问题,因为如果用户输入z或将其编号等级100放入,该怎么办?在构建用户界面时,我们必须始终假设用户会做一些愚蠢的事情。解决这些问题的最佳方法是将用户输入限制为仅预期的内容。在这种情况下,可接受的字母等级的下拉列表将起作用。或者,更好的是,范围控制如下所示:

// We'll set up two arrays with the same amount of elements and
// each position in each array corresponds to the value in the 
// same index position in the other array.
var scores = [4,   3,   2,   1,   0];
var grades = ["a", "b", "c", "d", "f"];

// Get all the sliders elements into an array
var inputs = Array.prototype.slice.call(document.querySelectorAll("input[type=range]"));

// Loop over the sliders and set up event handlers for each
inputs.forEach(function(input){
  input.addEventListener("input", function(){
    input.nextElementSibling.textContent = grades[input.value].toUpperCase();
  });
});

// Get a reference to the button
var btn = document.querySelector("input[type=button]");

// Set up your event handler in JavaScript, not in HTML
btn.addEventListener("click", function() {
  var sum = 0;
  // Loop over the inputs
  inputs.forEach(function(input){
     sum += scores[input.value];  
  });
  // As long as there is a sum, go ahead and divide it.
  document.getElementById("output").textContent = (sum / 6).toFixed(2);
});
.lbl { display:inline-block; width: 15em; }
input + span { display:inline-block; margin-left:1em; }
<div class="">
  <span class="lbl">Enter the first grade:</span><input type="range" min="0" max="4"><span>C</span><br> 
  <span class="lbl">Enter the seccond grade:</span><input type="range" min="0" max="4"><span>C</span><br> 
  <span class="lbl">Enter the third grade:</span><input type="range" min="0" max="4"><span>C</span><br>
  <span class="lbl">Enter the fourth grade:</span><input type="range" min="0" max="4"><span>C</span><br> 
  <span class="lbl">Enter the fifth grade:</span><input type="range" min="0" max="4"><span>C</span><br>
  <span class="lbl">Enter the sixth grade:</span><input type="range" min="0" max="4"><span>C</span><br>
</div>
<input type="button" value="Add">
<p id="output">"Grade 1"</p>

答案 1 :(得分:1)

您的问题是您尝试将字母'a'解析为数字,而不是,但您可以将值映射存储在对象中并使用输入字符作为引用的键您想要的值(请注意,此示例仅包含'a', 'b', 'c'的值,其他字符,空字符串,数字等仍会导致NaN):

var values = {
  a: 4,
  b: 5,
  c: 8
}

function call() {
  var y = values[document.getElementById("txt1").value];
  var yy = values[document.getElementById("txt2").value];
  var yyy = values[document.getElementById("txt3").value];
  var yyyy = values[document.getElementById("txt4").value];
  var yyyyy = values[document.getElementById("txt5").value];
  var yyyyyy = values[document.getElementById("txt6").value];
  var result = (y + yy + yyy + yyyy + yyyyy + yyyyyy) / 6;
  document.getElementById("output").innerHTML = result;
}
<center>
  <div class="">
    Enter the first number: <input type="text" id="txt1"/><br/> 
    Enter the seccond number: <input type="text" id="txt2"/><br/> 
    Enter the third number: <input type="text" id="txt3"/><br/>
    Enter the fourth number: <input type="text" id="txt4"/><br/>
    Enter the fifth number: <input type="text" id="txt5"/><br/>
    Enter the sixth number: <input type="text" id="txt6"/><br/>
  </div>
</center>
<center><input type="button" onclick="call()" value="Add" />
</center>
<p id="output"> "Grade 1"</p>

或者,如果您想添加一些错误处理并允许输入数字,您可以改进代码:

var values = {
  a: 4,
  b: 5,
  c: 8
}

function call() {
  var result = 0
  for(var i = 1; i <= 6; i++) {
    var k = document.getElementById("txt" + i).value;
    if(k in values) {
      result += values[k];
    }else if(!isNaN(document.getElementById("txt" + i).value)){
      result += parseInt(document.getElementById("txt" + i).value);
    }
  }
  document.getElementById("output").innerHTML = result / 6;
}
<center>
  <div class="">
    Enter the first number: <input type="text" id="txt1"/><br/> 
    Enter the seccond number: <input type="text" id="txt2"/><br/> 
    Enter the third number: <input type="text" id="txt3"/><br/>
    Enter the fourth number: <input type="text" id="txt4"/><br/>
    Enter the fifth number: <input type="text" id="txt5"/><br/>
    Enter the sixth number: <input type="text" id="txt6"/><br/>
  </div>
</center>
<center><input type="button" onclick="call()" value="Add" />
</center>
<p id="output"> "Grade 1"</p>

答案 2 :(得分:1)

如果要求用户在文本框中输入某些内容的名称,然后您想要查找与该名称相关联的数值,那么您应该使用对象属性,而不是变量来存储数据。 / p>

例如:

const grades = {A: 4, B: 3, C: 2, D: 1, F: 0};

然后当你从文本框中获得输入时,你会像这样查找值:

const y = grades[document.getElementById("txt1")];

如果您在文本字段中输入垃圾,您将获得NaN。

考虑使用单选按钮并为自己省去很多痛苦。