为什么我的程序不起作用?

时间:2017-04-30 20:44:39

标签: javascript

我试图编写一个简单的程序来计算数组中最大的偶数。

使用了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));
&#13;
&#13;
&#13;

请帮助我被困住了。该计划不会在Chrome中领先。

3 个答案:

答案 0 :(得分:2)

你给出了一个值,而不是比较:

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

你也回到了错误的元素:

&#13;
&#13;
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));
&#13;
&#13;
&#13;

这可能会有所帮助:

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

答案 1 :(得分:0)

您需要更改

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

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

答案 2 :(得分:0)

以下是您的问题的解决方案

> x <- c("gender_gender-1", "county-county-county-2")
> gsub("^(.*?)[,_\ -]\\1", "\\1", x)
[1] "gender-1"        "county-county-2"