我正在用 JavaScript 进行测试。我被要求执行以下操作:
function IsOffline (users, name) {
// The function called "IsOffline" receives as an argument an array of objects called 'users' and a string called 'name'.
// each object has a property 'name' which is a string and another called 'online' which is a boolean.
// The function must return true if the user is offline, otherwise false.
// ex:
// var users = [
// {
// name: 'toni',
// online: true
//},
// {
// name: 'emi',
// online: true
//},
// {
// name: 'john',
// online: false
//}
//];
//
// IsOffline (users, 'emi') return false
// Your code here:
我有点迷茫,不知道如何开始。感谢您的帮助。
答案 0 :(得分:0)
您可以使用 Array.find()
方法来搜索数组中的项目。
function IsOffline(users, name) {
const foundUser = users.find(user => user.name === name)
return foundUser ? !foundUser.online: "No user found";
}
var users = [
{ name: 'toni', online: true },
{ name: 'emi', online: true },
{ name: 'john', online: false },
];
// Online User
console.log(IsOffline(users, 'emi'))
// Offline User
console.log(IsOffline(users, 'john'))
// Unknown User
console.log(IsOffline(users, 'tom'))