最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Returning NULL from an empty array - Stack Overflow

programmeradmin3浏览0评论

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...

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...

Share Improve this question asked May 27, 2020 at 21:29 jonjohvaljonjohval 251 silver badge3 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 2

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]));

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));

In the second case, numbers = ([]) assigns the numbers to [] (which always return true) instead of paring 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 ment, there is another mistake, where you are using numbers instead of array in the function.

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;
    }
}
发布评论

评论列表(0)

  1. 暂无评论