我有一个包含 50 个用户的数组。 那么我有一个方法 showById:(应该登录到与 id 匹配的控制台用户对象,以防我们找不到用户它应该记录“无法找到 id 的用户:__”); 这是我所拥有的:
const users = [{
"id": 1,
"first_name": "Abner",
"last_name": "Glaisner",
"gender": "Male",
"language": "Tswana"
},
{
//...
}]
class UserList {
constructor(users) {
this.users = users;
}
showNames() {
users.forEach(function (user) {
console.log(user);
return this;
})
}
showById(id) {
users.forEach(function (user) {
if (id === user.id) {
console.log(user.first_name);
} else {
console.log(`Unable to find user id: ${id}`);
}
})
}
}
我期望当前用户输出一个对象,但我现在拥有的是当前对象和 49 次“无法找到用户 ID:__”;
最佳答案
考虑使用 Array find
method .
showById(id) {
let found = users.find(user => user.id === id);
if (!found) {
return console.log(`Unable to find user id: ${id}`);
}
console.log(found.first_name);
}
关于javascript - 如何使用 forEach 方法 console.log 正是我需要的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54243069/