简体   繁体   中英

ignoring empty strings when looping through an array in JavaScript

I am attempting to go through an array and add up all the numbers. I used console.log to show me what values the script was using as shown below. I keep trying different variations of things in the if() but nothing seems to be working properly.

    var billycount = 0;
    var billyTotalScore = billyScoreList.reduce(function(score, total) {
        if(score === " ") {
        billycount += 1;
        }
        return +total + +score; 
    });
    console.log(billycount); //0
    console.log(billyTotalScore); //30
    console.log(billyScoreList); // ["12", " ", "18"]
    console.log(billyAverageScore) //10

    var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);

The answer to billyAverageScore should equal 15 (30/2).

I tried if(score === "0") which gives me the same answers as above and if (score !== true) which gives me a count of 2 and an average of 30. I think reduce() is treating the empty string as a 0. I want to be able to count all the empty strings so I can discount them from the length when finding the average.

I have been wrestling this forever and feel like I'm missing one key concept behind it. Any help would be great! Thanks!

UPDATE:

For anyone who stumbles across this, here is the code I got to work.

var billycount = 0;
    var billyTotalScore = billyScoreList.reduce(function(total, score) {
        if (score === " " || total === " ") {
        billycount++;   
        }
        return +total + +score; 
    });

    var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);

When I was just checking if (score === " ") I was forgetting that score will never be equal to the first term in the array. I just added || total === " " || total === " " . the only time this would break down would be if the first element was " " and the second element was 0. I would want to billycount++ for the first element but not for the second. I'll have to give that some more thought.

The callback function of reduce should be function(total, score) instead of function(score, total) .

see MDN :

previousValue
    The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
    The current element being processed in the array.

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