该代码适用于一位数字但不适用于两位或三位数字,我该怎么做> ????我想这样做只是不使用math max函数。
问题主要在于它只考虑两位数字的第一位数字。那么我该怎么做才能将两位数字读成两位数并打印出最大值呢。
快速回复将不胜感激。
document.querySelector('.result').addEventListener('click',function(){
var val1, val2 , val3, val4, val5, val6, val7, val8;
var max = 0;
val1 = document.querySelector('#value1').value;
val2 = document.querySelector('#value2').value;
val3 = document.querySelector('#value3').value;
val4 = document.querySelector('#value4').value;
val5 = document.querySelector('#value5').value;
val6 = document.querySelector('#value6').value;
val7 = document.querySelector('#value7').value;
val8 = document.querySelector('#value8').value;
//console.log(val1);
var array = [val1, val2, val3, val4, val5, val6, val7, val8];
for(var i=0;i<8;i++){
if(array[i] > max)
{
max = array[i];
}
}
document.getElementById('totalt').value= max;
});
<!DOCTYPE html>
<html>
<body>
<div class="outer-block">
<em><h1>Biggest number</h1></em>
<h3>Enter marks</h3>
<div class="display"> FIRST NUMBER: </div>
<input type="text" placeholder="Number 1" class="marks" id="value1">
<div class="display"> SECOND NUMBER: </div>
<input type="text" placeholder="Number 2" class="marks" id="value2">
<div class="display"> THIRD NUMBER: </div>
<input type="text" placeholder="Number 3" class="marks" id="value3">
<div class="display"> FORTH NUMBER: </div>
<input type="text" placeholder="Number 4" class="marks" id="value4">
<div class="display"> FIFTH NUMBER: </div>
<input type="text" placeholder="Number 5" class="marks" id="value5">
<div class="display"> SIXTH NUMBER: </div>
<input type="text" placeholder="Number 6" class="marks" id="value6">
<div class="display"> SEVENTH NUMBER: </div>
<input type="text" placeholder="Number 7" class="marks" id="value7">
<div class="display"> EIGHTH NUMBER: </div>
<input type="text" placeholder="Number 8" class="marks" id="value8">
<input type="submit" value="GO" class="result">
<div class="display" id="totale">BIGGEST NUMBER</div>
<input type="text" id="totalt" class="marks">
</div>
</body>
</html>
答案 0 :(得分:1)
var array = [1,2,3,4,5];
// console.log(Math.max(...array))
let max = '';
array.forEach(x=> {
if(parseInt(x) > max){
max = x;
}
});
console.log(max);
&#13;
您可以将数组作为参数传播到Math.max
或者按照您的意愿传播,在执行检查之前使用forEach
循环和parseInt每个元素