总和输入字段具有字符中的存储号码



我需要总和输入字段,困难的是我需要将a=1 b=2 c=3存储到z,以便每个字符都有数字。输入字段是类似a的字符,并使用5总和a的数量并显示新字符。

我尝试了此代码,但我无法将数字存储在字符中:

<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<script type="text/javascript">
    function doMath()
    {
        var my_input1 = document.getElementById('my_input1').value;
        var my_input2 = document.getElementById('my_input2').value;
        var sum = parseInt(my_input1) + parseInt(my_input2);
        document.write(sum);
    }
</script>

function doMath() {
  var charMap = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
  }; //add more as needed
  // note I make NO attempt to ensure the entered value exists here.
  var my_input1 = document.getElementById('my_input1').value;
  var my_input2 = document.getElementById('my_input2').value;
  console.log(charMap[my_input1], charMap[my_input2]);
  var sum = charMap[my_input1] + charMap[my_input2];
  document.getElementById('showresult').innerHTML = sum;
}
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<div id="showresult"></div>

您可以使用charCodeAt获取字母的字符代码:

'a'.charCodeAt(0)  // 97

如果要为每个字符定义一个自定义号码,就必须声明一个对象:

let values = { a: 1, b: 2, c: 3 }
values.a // 1

最新更新