0

Understanding "defined" variables

Hi, I'm currently working on a problem with an Array. I was wondering if anyone can explain to me why 'breakfasts' isn't defined - when there is a defined array for this. Is it because it is in the main function and the {, are closed? I'm also unsure of when you need to use the this. ... lists. It's all very confusing! Any feedback on this code would be greatly welcomed: PROBLEM: The array you are given represents the menu of breakfast options available at the hotel. The Chef decided to replace one of the options with "Fluffy Pancakes". Write a program to take the index as input, replace the element with that index with "Fluffy Pancakes", and output the new menu to the console as an array. Sample Input 2 Sample Output [ 'Cinnamon Doughnuts', 'Waffles', 'Fluffy Pancakes', 'Chorizo Burrito', 'French Toast' ] The element with index 2 has been replaced in the output array. CODE (BELOW THE COMMENTS IS WHAT I HAVE WRITTEN) function main() { var breakfasts = ['Cinnamon Doughnuts', 'Waffles', 'Granola', 'Chorizo Burrito', 'French Toast']; var index = parseInt(readLine(), 10) //replace the corresponding element by "Fluffy Pancakes" //output the menu to the console } function cafe (breakfasts, index){ this.breakfasts = breakfasts; this.index = index; }; let newMenu = cafe.breakfasts.splice (index, 1, "Fluffy Pancakes"); console.log(newMenu);

28th Mar 2021, 3:59 PM
Leanne Smith
Leanne Smith - avatar
4 ответов
+ 3
Leanne Smith breakfasts is an array and you just need to store new breakfast item in that array and print breakfasts so you just need to do like this breakfasts [index] = 'Fluffy Pancakes'; console.log(breakfasts); ------------------- This is complete solution:- ------------------- function main() { var breakfasts = ['Cinnamon Doughnuts', 'Waffles', 'Granola', 'Chorizo Burrito', 'French Toast']; var index = parseInt(readLine(), 10) //replace the corresponding element by "Fluffy Pancakes" //output the menu to the console breakfasts[index] = "Fluffy Pancakes"; console.log(breakfasts); }
28th Mar 2021, 4:08 PM
A͢J
A͢J - avatar
28th Mar 2021, 4:00 PM
A͢J
A͢J - avatar
+ 2
Thanks for letting me know the solution. I would never have thought to do that!
28th Mar 2021, 4:30 PM
Leanne Smith
Leanne Smith - avatar
0
This is how i did it. function main() { var breakfasts = ['Cinnamon Doughnuts', 'Waffles', 'Granola', 'Chorizo Burrito', 'French Toast']; var index = parseInt(readLine(), 10) breakfasts.splice(index,1,'Fluffy Pancakes'); console.log(breakfasts); }
23rd Dec 2021, 9:08 AM
Samnith Vath
Samnith Vath - avatar