我需要帮助来解决这个问题。这是原始代码:
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.
}
我在这里不了解什么?认为某件事有意义并发现它“不起作用”,这真让我感到烦恼。请帮忙。谢谢大家。
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;
[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.
}
if (treatsArr.indexOf('cookie') > -1)
或
if (treatsArr.includes('cookie'))