jeudi 12 décembre 2019

Using If...Else Statements, arrays, and indexOf() in Javascript [duplicate]

This question already has an answer here:

I need help breaking this down. Here is the original code:

function hasTreat(treat) {
  const treatsArr = ['cookie', 'cake', 'muffin', 'pie', 'ice cream'];
  if (treatsArr.indexOf(treat) === true) {
    return true;
  }
  return false;
}
if (hasTreat("cookie")) { // You should have a cookie. 
  console.log("You have a cookie!");
} else {
  console.log("You have no cookie."); // This is wrong. You should have a cookie. 
}

I've modified it to this:

function hasTreat(treat) {
  const treatsArr = ['cookie', 'cake', 'muffin', 'pie', 'ice cream'];
  if (treatsArr.indexOf('cookie') === true) {
    return true;
  } else {
    return false;
  }
}
if (hasTreat('cookie')) { // You should have a cookie. 
  console.log("You have a cookie!");
} else {
  console.log("You have no cookie."); // This is wrong. You should have a cookie. 
}

What in the world am I not understanding here? It bugs me so much to think that something makes sense and to find out it doesn't "work". Help, please. Thanks, guys.

Aucun commentaire:

Enregistrer un commentaire