简体   繁体   中英

Returning String from if statement in forEach loop is undefined

in this code, I used a forEach loop inside the function to iterate over the arrays at the bottom. Basically, if the array contains the string June, I should return "Summer Break, else return. "Have a great day," My only restriction for this exercise. is to not use a variable to store the result I am returning.

I think my issue lies somewhere in the return sections of the if/else statements. From the console I get undefined. Is it because a forEach loop returns undefined? What would you use as a suggestion? Filter? A for loop? While loop?

Any tools in the future I can use to diagnose this?

 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!"

You can use Array.prototype.includes to check if an element is present in the array.

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

You can use 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));

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