在Javascript中计算枪在一定范围内射击的高程

时间:2017-04-14 08:37:37

标签: javascript html

对某些人来说这似乎很简单,但我无法理解它。

如果我们有枪支射击的以下信息:

范围提升
100米 - 50
200米 - 76
300米 - 110
400m - 140

在用户使用Javascript输入0-400之间的数字后,我们如何编程才能找到Elevation?

提前感谢您的任何答案!

2 个答案:

答案 0 :(得分:0)

function cal() {

var constants = [50,76,110,140]; // An array of elevation heights at 100,200...

var input = document.getElementById('input').value;

if ( input == (constants.length * 100 )) {  // Exception case
  console.log(constants[constants.length-1]);
} else { 
for ( var i = 0; i < constants.length; i++ ) { 
  if ( String(input).charAt(0) == (i+1)) { // Check first digit of input
    console.log((input - ((i+1)*100))/100 * (constants[i+1]-constants[i]) + constants[i]); 
}}}}
<input id="input" onchange="cal()">

答案 1 :(得分:0)

例如,需要一个现代浏览器。

&#13;
&#13;
const data = [
  [100, 50],
  [200, 76],
  [300, 110],
  [400, 140],
];

const lookup = {
  0: () => 0
};
let previousPair = [0, 0];
for (let pair of data) {
  const [range, elevation] = pair;
  const [pRange, pElevation] = previousPair;
  lookup[range] = value => {
    const percRange = (value - pRange) / (range - pRange);
    const extraElevation = (elevation - pElevation) * percRange;
    return pElevation + extraElevation;
  };
  previousPair = pair;
}

const submitHanler = event => {
  event.preventDefault();
  const range = new FormData(event.target).get('range');
  for (let key of Object.keys(lookup)) {
    if (range <= key) {
      return (document.getElementById('elevation').value = lookup[key](range));
    }
  }
};

document.getElementById('calculate').addEventListener('submit', submitHanler, false);
&#13;
#calculate>input {
  width: 5em;
}
&#13;
<form id="calculate">
  <label for="range">Range</label>
  <input name="range" type="number" min="0" max="400" placeholder="0 to 400" required />
  <button type="submit">Calculate</button>
</form>
<input id="elevation" readonly />
&#13;
&#13;
&#13;