我试图理解为什么当我在任何数组上调用maxofThree时,会返回undefined?我是JS的新手,所以感谢你的帮助!
function maxofThree (array) {
for (var i; i < array.length; i++) {
var largestNumber = 0;
if (array[i] > largestNumber) {
largestNumber = array[i];
}
return largestNumber;
}
}
答案 0 :(得分:4)
你必须在循环后返回,你必须从零开始i
。
function maxofThree(array) {
var largestNumber = array[0];
for (var i=0; i < array.length; i++) {
if (array[i] > largestNumber) {
largestNumber = array[i];
}
}
return largestNumber;
}
作为旁注,您可以使用Math.max
获取最大数字
function maxofThree(array) {
return Math.max.apply(null, array);
}
答案 1 :(得分:0)
function maxofThree (array) {
for (var i; i < array.length; i++) { //the variable i is not initialized i==undefined
//At each loop you increment i==undefined undefined++ equals to NaN
//So i at first loop is undefined, at second loop is NaN
//undefined < any number except 0, NaN < any number is always false, so the loop is executed only one time
var largestNumber = 0; //At each loop you initialize/reset the variable largestNumber to 0
if (array[i] > largestNumber) {
largestNumber = array[i]; //i is NaN, array[NaN]==undefined
//So largestNumber is always undefined
}
return largestNumber; //You return largestNumber before next loop occurs, you return undefined
//The next loop never occurs, because you have done a return
}
}
固定代码:
function maxofThree (array) {
var largestNumber = 0; //Initialize largestNumber to 0 before loops occurs
// I suppose all numbers are positive, otherwise you need to rethink the solution
for (var i=0; i < array.length; i++) { //Initialize i to 0
//At each loop i is incremented until i < array.length
if (array[i] > largestNumber) {
largestNumber = array[i];
}
//The next loop will occurs
}
return largestNumber; //At the end of loop you return the largestNumber
}
答案 2 :(得分:0)
您没有初始化i
,因此默认情况下它是undefined
。进行比较i < array.length
时,undefined
会转换为数字NaN
(不是数字),因此表达式的计算结果为false
。这意味着你永远不会进入循环,并且在完成函数之前从未点击return语句,因此返回undefined
。
您应该将i
初始化为0
。在那之后,还有两个问题。
在循环开始时将0
分配给largestNumber
意味着它会在每次迭代时重置为0
。您应该将该语句移到循环之前。
此外,在循环中使用return
会导致函数在第一次迭代结束时立即返回。您应该将该语句移动到循环之后执行。
虽然我们正在使用它,但您应该重命名该功能。它并不像你真正限制自己的3个元素(不是你应该的)。此外,array
过于通用。他们需要成为数字,对吧?所以称他们为numbers
。
您的功能应如下所示:
function maximum(numbers) {
var largestNumber = 0;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > largestNumber) {
largestNumber = numbers[i];
}
}
return largestNumber;
}