--- id: 587d7b7d367417b2b2512b1d title: 'Iterate Through the Keys of an Object with a for...in Statement' challengeType: 1 videoUrl: '' localeTitle: 使用for ... in Statement中的对象键迭代 --- ## Description
有时您可能需要遍历对象中的所有键。这需要JavaScript中的特定语法,称为for ... in语句。对于我们的users对象,这可能看起来像:
for(让用户在用户中){
的console.log(用户);
};

//日志:
艾伦
杰夫
莎拉
瑞安
在这个语句中,我们定义了一个变量user ,正如您所看到的,在每次迭代期间,当该语句循环遍历该对象时,该变量被重置为每个对象的键,从而导致每个用户的名称被打印到控制台。 注意:
对象不像数组那样保持对存储键的排序;因此,当引用或访问该密钥时,对象上的键位置或其出现的相对顺序是无关紧要的。
## Instructions
我们定义了一个函数countOnline ;在此函数中使用for ... in语句循环访问users对象中的users并返回其online属性设置为true的用户数。
## Tests
```yml tests: - text: users对象包含用户JeffRyanonline设置为true ,用户AlanSarah online设置为false testString: 'assert(users.Alan.online === false && users.Jeff.online === true && users.Sarah.online === false && users.Ryan.online === true, "The users object contains users Jeff and Ryan with online set to true and users Alan and Sarah with online set to false");' - text: 函数countOnline返回online属性设置为true的用户数 testString: 'assert((function() { users.Harry = {online: true}; users.Sam = {online: true}; users.Carl = {online: true}; return countOnline(users) })() === 5, "The function countOnline returns the number of users with the online property set to true");' ```
## Challenge Seed
```js let users = { Alan: { age: 27, online: false }, Jeff: { age: 32, online: true }, Sarah: { age: 48, online: false }, Ryan: { age: 19, online: true } }; function countOnline(obj) { // change code below this line // change code above this line } console.log(countOnline(users)); ```
## Solution
```js // solution required ```