【问题标题】:JavaScript testing: change Boolean value into an array of objectJavaScript 测试:将布尔值更改为对象数组
【发布时间】:2021-07-05 12:13:00
【问题描述】:

我正在用 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:
  

我有点迷茫,不知道如何开始。感谢您的帮助。

【问题讨论】:

标签: javascript arrays testing boolean javascript-objects


【解决方案1】:

您可以使用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'))

【讨论】:

  • Ehm... 当用户 on 在线状态为 @ 时,您返回的结果与预期的完全相反,因为用户 offline 987654323@ ;)
  • @secan 是的!愚蠢的错误,已解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2012-12-30
  • 2011-08-13
  • 1970-01-01
  • 2023-01-27
  • 2017-06-04
相关资源
最近更新 更多