在Java中使用If…Else语句,数组和indexOf()[duplicate]

问题描述 投票:-1回答:2

我需要帮助来解决这个问题。这是原始代码:

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. 
}

我已将其修改为:

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. 
}

我在这里不了解什么?认为某件事有意义并发现它“不起作用”,这真让我感到烦恼。请帮忙。谢谢大家。

javascript if-statement indexof
2个回答
0
投票

indexOf()方法返回可以在数组中找到给定元素的第一个索引;如果不存在,则返回-1(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)。

所以您的支票可能应该是:

  if (treatsArr.indexOf(treat) >= 0) {
    return true;
  }
  return false;

0
投票

[indexOf返回元素的索引,而不是boolean值,对于布尔值,可以使用includes

尝试一下:

function hasTreat(treat) {
  const treatsArr = ['cookie', 'cake', 'muffin', 'pie', 'ice cream'];
  if (treatsArr.includes('cookie')) {
    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. 
}

0
投票
if (treatsArr.indexOf('cookie') > -1) 

if (treatsArr.includes('cookie')) 
© www.soinside.com 2019 - 2024. All rights reserved.