简体   繁体   English

使用 for...in 语句遍历 object 的键

[英]Iterating through the Keys of an object with a for…in Statement

Given this object and for...in statement, my expected output of countOnline is false .鉴于此 object 和for...in语句,我预期的 countOnline 的countOnlinefalse We are iterating and the online key for other object entries has been changed to the value 33. Why are we getting true back when we have a strict equality check for boolean?我们正在迭代,其他 object 条目的在线密钥已更改为值 33。当我们对 boolean 进行严格的相等检查时,为什么我们会返回true

let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: 33
  },
  Sarah: {
    age: 48,
    online: 33
  },
  Ryan: {
    age: 19,
    online: 33
  }
};

function countOnline(usersObj) {

  for (let user in users) {
    if (users[user].online === true) {
      return true;
    } else {
      return false;
    }
  }
}

console.log(countOnline(users));

The first element in your array has online: true , and your function returns when it finds a user with online: true ... so it just stops the loop and returns with true on the first iteration:)数组中的第一个元素具有online: true ,并且您的 function 在找到具有online: true的用户时返回...所以它只是停止循环并在第一次迭代时返回 true :)

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

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