javascript - 通过键盘输入 2 个数字,并使用 Math ? 显示最大/最小和幂级。

标签 javascript

场景如下:用户在每个框中输入两个数字,然后从 Min、Max 和 pow 框中进行选择。数字不受限制,通过键盘输入,可以是任意整数,结果应该是Max/Min/Pow。我已经准备好了选项框和布局,但我无法获得结果,因为它要么给出“NaN”,要么什么也不给出。

有人可以帮忙找出我的代码中的错误吗?

<script>
		function calc(){
			var num1 = parseInt(document.getElementById('num1').value);
			var num2 = parseInt(document.getElementById('num2').value);
			var oper = document.getElementById('operators').value;

			if(oper === 'min')
			{
			document.getElementById('result').value = Math.min;
			}
		}	
	</script>
<select id="operators">
	<option value="min">Math.min</option>
	<option value="max">Math.max</option>
	<option value="pow">Math.pow</option>
</select>

<input type="text" id="num1" value="">

	<input type="text" id="num2" value="">	
	<button onclick="calc();">Evaluate 2 input function</button>
	<br><br>

最佳答案

您需要为 Math.min() 提供参数

 document.getElementById('result').value =  Math.min(num1, num2)

查看代码片段:

function calc() {
  var num1 = parseInt(document.getElementById('num1').value);
  var num2 = parseInt(document.getElementById('num2').value);
  var oper = document.getElementById('operators').value;

  if (oper === 'min')
    document.getElementById('result').innerText = Math.min(num1, num2);
  else if (oper === 'max')
    document.getElementById('result').innerText = Math.max(num1, num2);
  else
    document.getElementById('result').innerText = Math.pow(num1, num2);
}
<select id="operators">
  <option value="min">Math.min</option>
  <option value="max">Math.max</option>
  <option value="pow">Math.pow</option>
</select>

<input type="text" id="num1" value="">

<input type="text" id="num2" value="">

<button onclick="calc();">Evaluate 2 input function</button>
<br><br>

<h1 id="result"></h1>

关于javascript - 通过键盘输入 2 个数字,并使用 Math ? 显示最大/最小和幂级。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896810/

相关文章:

JavaScript 无法在任何浏览器中运行且已启用 - 已替换 document.write 作为警报,但仍然无法工作

javascript - 如何知道在 *ngFor 循环中单击了哪个按钮?

Javascript if语句为假,但代码正在执行

javascript - 创建 Angular 树控件时使用 json 作为数据源

javascript - Angular Material md-contact-chips 回调问题

javascript - 如何在点击div时执行代码?

javascript - 汇总构建后 : regeneratorRuntime is not defined

javascript - Vue - Nuxt - 如何在布局上调用中间件?

javascript - 取消导致散列更改或 HTML 5 历史记录更改的后退或前进事件

javascript - 如何检测鼠标何时停止在 React 中移动?