为什么我的功能没有返回准确计数?

时间:2015-04-01 14:35:02

标签: javascript arrays

扩展代码我一直在努力寻找补充跟踪器,但我目前的功能并没有返回大于平均值''的精确计数数,也没有返回低于平均值的整数计数。我还在代码中注释了两个问题,因为我不太明白为什么数组被设置为索引[0]。我从评论中学到了很多,并在这里寻找答案。非常感谢这个网站存在!希望通过这个问题有所学习。

function suppArray() {
var nums = new Array(); //create array 
var sum = 0; //variable to hold sum of integers in array
var avg = 0; //variable to hold the average
var i; 
var count = 0;
var count2 = 0;
var contents = ''; //variable to hold contents for output 

    var dataPrompt = prompt("How many numbers do you want to enter?", "");
    dataPrompt = parseInt(dataPrompt);

    for(i = 0; i <= dataPrompt - 1; i++) { //loop to fill the array with numbers 
        nums[i] = prompt("Enter a number","");
        nums[i] = parseInt(nums[i]);
        contents += nums[i] + " "; //variable that will be called to display contents
        sum = sum + nums[i];
    }
        avg = sum / nums.length; 
    for(i = 0; i < nums.length; i++) { //loop to find the largest number
        var biggest = nums[0]; //why does this have to be index 0 and not 'i' ?
        if(nums[i] > biggest) 
        biggest = nums[i]; //largest integer in array
    }
    for(i = 0; i < nums.length; i++) { //loop to find smallest integer
        var smallest = nums[0]; //why does this have to be the index 0 and not 'i' ??
        if(nums[i] < smallest) 
        smallest = nums[i]; //smallest integer in array
    }       
    for(count = 0; count < nums.length; count++) { //count of numbers higher than average
        if(nums[i] > avg) 
        count = nums[i];
    }   
    for(count2 = 0; count2 < nums.length; count2++) { //count of numbers lower than average
        if(nums[i] < avg)
        count2 = nums[i];
    }
}

1 个答案:

答案 0 :(得分:2)

您的功能并未返回正确的值,因为您正在分配countcount2。如果您在最后count完成代码并且count2将等于nums.length。这是因为您在for循环中使用它们。同样在循环中,您引用i,此时(我相信)此时也等于nums.length

我想你想要这样的东西:

count = 0;
count2 = 0;

for(i = 0; i < nums.length; i++) 
{
    if(nums[i] > avg)
    {
        count++; //Increase the count of numbers above the average
    }
    else if(nums[i] < avg)
    {
        count2++;  //Increase the count of numbers below the average
    }
}   

您可能希望对scopefor循环进行一些阅读,因为您似乎对它们感到有些困惑。

修改

如果你想要数组中最大和最小的值,你可以这样做:

//Assign the values to the first element by default
var biggest = nums[0];
var smallest = nums[0];

for(var i = 1; i < nums.length; i++)
{
    //Set biggest to the larger number, either biggest or the current number
    biggest = Math.max(biggest, nums[i]);
    //Set smallest to the smaller number, either biggest or the current number
    smallest = Math.min(smallest, nums[i]);
}

注意:这假设您在数组中至少有一个值