简体   繁体   English

继续获取数组中的元素数量作为一个javascript

[英]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我正在尝试获取登录的人数,并且我有一个循环遍历列表并带有条件,但它将数组中的元素数显示为 1

I have tried using the forEach Loop and the for loop counter我曾尝试使用 forEach 循环和 for 循环计数器

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预期的结果是 2,但我一直在我的控制台中得到 1 和一个小圆圈,里面有 2,但它在 DOM 中输出为 1

const creates a block scope variable, so every time (employee.clockIn == true) evaluates to true , arr is recreated as an empty array. const创建一个块作用域变量,因此每次(employee.clockIn == true)评估为truearr都会重新创建为空数组。 You should either create arr in the outer scope, or use more a functional approach, for example leveraging Array.prototype.filter :您应该在外部范围内创建arr ,或者使用更多的函数式方法,例如利用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一种更简单的方法可能是使用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);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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