简体   繁体   中英

Keep getting number of elements in the array as one javascript

I'm trying to get the number of people logged in and i have a loop going through the list with a condition but it displays the number of elements in the array as one

I have tried using the forEach Loop and the for loop counter

employees.forEach(employee => {
        if(employee.clockIn == true){
          const arr=[]
          arr.push(employee.firstName)
          console.log(arr.length);
        }
      })

The expected result is two but i keep getting 1 and a small circle that has 2 inside in my console but it outputs as 1 in the DOM

const creates a block scope variable, so every time (employee.clockIn == true) evaluates to true , arr is recreated as an empty array. You should either create arr in the outer scope, or use more a functional approach, for example leveraging Array.prototype.filter :

const clockedInEmployees = employees.filter(emp => emp.clockIn);
console.log(clockedInEmployees.length)

As suggested you are creating a new array every iteration of your loop.

An easier way to do this might be by using filter

var clockInEmployees = employees.filter(employee => employee.clockIn);

You are re creating the array on each iteration, you might want to hoist the declaration of the array outside the loop:

const arr = [];
employees.forEach(employee => {
    if(employee.clockIn == true){      
        arr.push(employee.firstName)
        console.log(arr.length);
    }
});

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