未定义从 forEach 循环中的 if 语句返回字符串

问题描述

在这代码中,我在函数内部使用了一个 forEach 循环来遍历底部的数组。基本上,如果数组包含字符串 June,我应该返回“Summer Break!否则返回,“祝你有美好的一天。”我对这个练习的唯一限制是不使用变量来存储我返回的结果。>

我认为我的问题在于 if/else 语句的返回部分。从控制台我得到未定义。是因为 forEach 循环返回 undefined 吗?你会用什么作为建议?筛选? for 循环? while 循环?

将来我可以使用任何工具来诊断这个问题吗?

function holidayDays(arr) {

  arr.forEach(function(items) {
    if (items === "June") {
      return "Summer Break!";
    } else {
      if (items !== "June")
        return "Have a great day!";
    }

  });

}


// Uncomment these to check your work!
const months = ["April","May","June","October"];
const animals = ["Cats","Dogs","Pigs"];
console.log(holidayDays(months)); // should return: "Happy Halloween"
console.log(holidayDays(animals)); // should return: "Have a great day!"

解决方法

您可以使用 Array.prototype.includes 检查数组中是否存在元素。

const holidayDays = (arr) => {
  return arr.includes('June') ? 'Summer Break!' : 'Have a great day!'
}

const months = ['April','May','June','October']
const animals = ['Cats','Dogs','Pigs']

console.log(holidayDays(months))
console.log(holidayDays(animals))

,

您可以使用 Array.prototype.some()

const holidayDays = (arr) =>
  arr.some((item) => item === "June") ? "Summer Break!" : "Have a great day!";

const months = ["April","May","June","October"],animals = ["Cats","Dogs","Pigs"];
console.log(holidayDays(months));
console.log(holidayDays(animals));