Skip to content
Advertisement

How would I define a function for this? [Noob question]

I´m working on creating a list for a game I play with my friends where words get added x times to that list. Currently, I´m using the same three lines of code 5 times and I´d like to instead just call up a predefined funtion 5 times. is that possible? (I only translated the first line)

JavaScript

Any help or pointing out where I mightve gone wrong would be appreciated!

Advertisement

Answer

A bigger sample of your script maybe would have helped, but from my understanding of your script if I had this problem I would do this:

JavaScript

You can see that I used f-strings here. f-strings allow you to put variables in strings without having to use + or , and have lots of double-quotes. I recommend that you use f-strings everywhere you can.

There is a problem though, and that’s the fact that you need to know the singular and plural of the fruit. But it can be solved like this:

JavaScript

To use this function you just have to do this: newList = fruitFunction('apple', 'apples', newList) Keep in mind that you have to have a list already made to call this function.

Also, it might be a good idea to instead of adding a fruits name 5 times for example in the list, you can append a list to the list. The list would contain the name of the fruit and the amount. It can be done like this:

JavaScript

And that should work, thanks.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement