简体   繁体   中英

Returning NULL from an empty array

I'm currently learning basic web development with JavaScript, taking an online course which corrects code using a bot. I'm trying to implement a function which calculates the average value of an array.

let numbers = [1,2,3]
function average(array){
    var total = 0;
    var count = 0;

    array.forEach(function(item){
        total += item;
        count++;
    })    

    if (numbers.length > 0){
        return total / count; 
    } else if (numbers = ([])) {
        return null 
    }

}

The code works fine, in practice, but I get an error returned saying 1) defines average such that average([]) returns null , as in if an empty array is sent in, average([]) is supposed to return null I can't figure out how to fix it...

In the second case, numbers = ([]) assigns the numbers to [] (which always return true ) instead of comparing it. The right way would be using == as follows:

 let numbers = [1,2,3] function average(array){ var total = 0; var count = 0; array.forEach(function(item){ total += item; count++; }) if (array.length > 0){ return total / count; } else if (array.length == 0) { return null } } console.log(average(numbers)); numbers = []; console.log(average(numbers));

EDIT:

As mentioned in the comment, there is another mistake, where you are using numbers instead of array in the function.

You don't need to test for [] . If the array has a length of zero, then it's empty:

 let numbers = [1, 2, 3] function average(array) { var total = 0; var count = 0; // No need to iterate over array if it's empty if (array.length > 0) { array.forEach(function(item) { total += item; count++; }) return total / count; } else { // If we got here, array.length === 0 return null } } console.log(average(numbers)); numbers = []; console.log(average(numbers));

I would make it way more simpler without the counter. You have the total in the length of the array.

I also added a version using array.reduce() .

And please, don't use numbers variable inside the function. It makes no sense here. You pass the variable to the function and inside the function you should use the received variable or it will behave incorrectly. Inside the function numbers is called "arr", so use arr all the way.

 function average(arr){ if (arr.length === 0) return null; let total = 0; arr.forEach(function(item){ total += item; }) return total / arr.length; } // using array.reduce() which makes more sense here function average2(arr){ if (arr.length === 0) return null; const total = arr.reduce(function(prev,next){ return prev + next; }); return total / arr.length; } console.log(average([])); console.log(average([1,2,3])); console.log(average2([])); console.log(average2([1,2,3]));

The reason, why your test case fails, is that you define numbers at the top and then reuse it within the function. That way it always returns the same. You should use array within the function instead.

Here a short version of your script to see, what js is capable of.

 function average(array){ let total = array.reduce((acc, value) => acc + value, 0); return array.length > 0? total / array.length: null; } console.log(average([1,2,3])) console.log(average([]))

  • You are using numbers instead of array inside average() method.
  • It could be possible that your array can be undefined. Try using this
function average(array) {
    if (typeof array == "object" && array.length > 0) {
        var total = 0;
        var count = 0;
        array.forEach(function(item) {
            total += item;
            count++;
        });
        return total / count;
    } else {
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM