2017-04-30 63 views
-3

我正試圖編寫一個簡單的程序來計算數組中最大的偶數。使用10個元素的數組。爲什麼我的程序無法正常工作?

function biggestEven(array) {  
 
    var numberOfNumbers = array.length; 
 
    var biggestYet = 0; 
 
    var theNumber; 
 
    for (var i = 0; i < numberOfNumbers; i++) { 
 
    if(array[i] % 2 = 0) { 
 
     biggestYet = array[i]; 
 
    } 
 
    if(array[i] % 2 = 0 && array[i] > biggestYet) { 
 
     theNumber = biggestYet; 
 
    } 
 
    } 
 
    return theNumber; 
 
} 
 
var myArray = []; 
 
for (var i = 0; i < 10; i++) {  
 
    myArray[i] = window.prompt("Enter number " + (i+1) + "of 10:"); 
 
} 
 
console.log("The biggest even number is: " + biggestEven(myArray));

請幫我卡住了。該計劃不會導致鉻。

回答

2

你給一個值,而不是比較:

if(array[i] % 2 = 0) { 
    biggestYet = array[i]; 
} 

,你也正在返回的錯誤的元素:

function biggestEven(array) { 
 
    var numberOfNumbers = array.length; 
 
    var biggestYet = 0; 
 
    var theNumber = 0; 
 
    
 
    for (var i = 0; i < array.length; i++) { 
 
    if (array[i] % 2 === 0) { 
 
     biggestYet = array[i]; 
 
    } 
 
    
 
    if (array[i] % 2 === 0 && array[i] > biggestYet) { 
 
     theNumber = biggestYet; 
 
    } 
 
    } 
 
    return biggestYet; 
 
} 
 

 
var myArray = []; 
 

 
for (var i = 0; i < 2; i++) {  
 
    myArray[i] = window.prompt("Enter number " + (i+1) + " of 10:"); 
 
} 
 

 
console.log("The biggest even number is: " + biggestEven(myArray));

這可能幫助:

console.log(Math.max(...[267, 306, 108, 307].filter(function(value) { return value % 2 === 0 })));

+1

你是中途。請說明出了什麼問題以及如何解決問題 –

0

您需要更改

if(array[i] % 2 = 0) { 
    biggestYet = array[i]; 
} 

if(array[i] % 2 == 0) { 
    biggestYet = array[i]; 
} 
0

這裏是你的問題的解決方案

function biggestEven(array) { 
 
    \t return Math.max(...array.filter(function(num){ 
 
     \t \t return num%2==0; 
 
    \t \t })); 
 
    } 
 
    var myArray = [1,2,36,45,51,16,7]; 
 
    alert(biggestEven(myArray));

相關問題