简体   繁体   中英

JavaScript testing: change Boolean value into an array of object

I'm doing a test in JavaScript. I'm asked to do the following:

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:
  

I'm a little lost and I don't know how to start. I appreciate any help.

You can use the Array.find() method which lets you search for an item in the array.

 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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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