简体   繁体   English

为什么调用 object 的属性在 for of 循环中不起作用?

[英]Why calling a property of an object doesn't work in the for of loop?

In this code, I'm trying to call the.password property from the object subsequently with all objects within the array.在此代码中,我试图随后使用数组中的所有对象从 object 调用 .password 属性。 However, if I'm doing this within the "for of" loop, it doesn't work.但是,如果我在“for of”循环中执行此操作,则它不起作用。 But out of the "for of" loop, no issues occur and works as expected.但是在“for of”循环之外,没有问题发生并且按预期工作。

Is there a reason why it doesn't do the magic properly?为什么它不能正确发挥魔法是有原因的吗?

 let users = [ {name: "Paul", login: "cheerfullime", password: "qqwerty11"}, {name: "Jack", login: "jackdaniels", password: "browser22"}, ] let counter = 0; for (let user of users) { console.log(user[counter].password);// This one returns an error counter ++; } users[0].password;//But the same thing out of the for of loop works fine

You iterate the elements of the array with for... of statement and you can use this object for getting the password.您使用for... of语句迭代数组的元素,您可以使用此 object 来获取密码。

 let users = [{ name: "Paul", login: "cheerfullime", password: "qqwerty11" }, { name: "Jack", login: "jackdaniels", password: "browser22" }], counter = 0; for (let user of users) { console.log(user.password); counter++; }

Here, user is an object and you are trying to access its property using array notation.在这里, user是 object,您正在尝试使用数组表示法访问其属性。 You should use:你应该使用:

  users.forEach (function (user) {
    console.log(user.password);
  }
)

Or, you can also do it as:或者,您也可以这样做:

  for (let counter=0; counter<users.length;counter++) {
    console.log(users[counter].password); // use 'users' instead of user
  }

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

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