I am extremely new to coding and I am currently working on iterating over arrays. I am not sure why I am having trouble with this logic as I can already do a bunch of other stuff with arrays. I think I am forgetting some of the basics.
I am wanting to be able to print one of these array elements multiple times, either as a 'spam' e.g. printing out "Wave 1" 5 times in a row, or having a function that takes in a (num) and then spams it (num) times.
Here is the array:
const friendlyEmotes = ["Wave 1", "Wave 2", "Flirt 1", "Flirt 2", "Dance 1", "Dance 2", "High-five", "Laugh"]
And this is my code:
const spamWave = function(num){
for (let i = 0; i < num; i++){
return friendlyEmotes[0];
}
}
I realize I am not using 'i' in the return statement and therefore am not utilizing the loop, but that is where I am missing the logic or syntax in order to use 'i' to print out the element multiple times.
I tried indexOf with using [i] without success:
const spamWave = function(num){
for (let i = 0; i < num; i++){
return friendlyEmotes.indexOf(0)[i];
}
}
// spamWave(5) returns 'undefined'
I hope I was able to make my question clear and concise.
Any advice would be much appreciated.
You are returning the array element instead of logging it to the console. This should work for you: it's a function which takes an array, an index of the item in the array to log, and the number of times to log the element at the index:
const friendlyEmotes = ["Wave 1", "Wave 2", "Flirt 1", "Flirt 2", "Dance 1", "Dance 2", "High-five", "Laugh"];
function logArrayElementAtIndex (arr, index, logCount) {
for (let i = 0; i < logCount; i += 1) {
console.log(arr[index]);
}
}
logArrayElementAtIndex(friendlyEmotes, 0, 5);