我知道一个循环会重复指定的次数,但是我怎么做才能让它读取整个数组并返回某个值呢?我试图返回两个测试题的最大值,但我得到的唯一结果是数组的第一个值。
function question1(numberArray) {
for (let i = 0; i < numberArray.length; i = i + 1) {
number = numberArray[i];
return number;
}
}
function testQuestion1() {
let testArray = [10, 45, 33, 67, 433, 33];
let answer1 = question1(testArray);
if(question1(testArray) == 433) {
console.log("Question 1:Found the largest");
} else {
console.log("Question1: For array ", testArray, " returned ", answer1, "Which is not the largest");
}
let testArray2 = [10, -900, 3000, 22, 33, 67, 433, 33];
let answer2 = question1(testArray);
if(question1(testArray2) == 3000) {
console.log("Question 1: Found the largest");
} else {
console.log("Question 1: For array ", testArray2, " returned ", answer2, "Which is not the largest");
}
}发布于 2020-10-31 19:16:39
将Math.max与数组扩展运算符一起使用(也在链接中):
function myMax(numberArray) {
return Math.max(...numberArray);
}使用for循环和max变量:
function myMax(numberArray) {
var max=-Infinity;
for(var i=0; i<numberArray.length; i++)
if(numberArray[i]>max)
max=numberArray[i];
return max;
}使用reduce
function myMax(numberArray) {
return numberArray.reduce((max, arrayItem)=>Math.max(max, arrayItem),-Infinity);
}所有情况下,如果numberArray为空,则返回-Infinity。
https://stackoverflow.com/questions/64619302
复制相似问题