Hey dont worry man, confusion is part of learning and trust me it gets even more confusing …
I have to say, I didnt read the assesment, I just read that it was a sum, but hey, here is what I wrote up. Using the for loop,
//[1] Remove the last Item in the Array
myArray.pop();
//[2] Add new name to list (keeping inline with the Street fighter theme, what a game that first one was...ah nostalgia)
myArray.push('Eagle');
myArray.push('Gen');
// [3] Loop over the array.
function printNames(array){
let string = ``;//String literals are really easy to build up
for(let index = 0; index < array.length; index++){
let name = array[index]//Need to store the name at each call
string += `${name} (${index})`; // This then builds the string out
}
return string //This returns the string.
}
The Array.forEach() is a built in JS function(method) that lives in the Array object. Its been put in to cut down on the amount of for...
loops that people have to write.
array.forEach() takes an array and goes through each entry in the arrya step by step. So you have and array [1 , 2, 3, 4]
really this is [(0) : 1, (1) : 2, (2) : 3, (3) : 4 ]
. the method goes in an ascending order. It doesnt care if the array is sorted or not. So it’s good practice to run an sorted array through it using the Array.sort()
.
The method breaks down the array into smaller array’s [(0) : 1] [(1) : 2]...
At each call, it would apply any function we give it. Using an arrow function (anonymous function) we can give it the parameters, and it really only has two (index ,value)
so the method would look like this:
function printEachName(array){
//This is is where the string will be stored
let string = ``;
array.forEach((index, name)=>{
//Takes the index and the value of each array item as it iterates through the array,
string += ` ${index} (${name}) `;//Building the string out
})
return string;//Returns the String
}
I hope that helps man =)
(my sleeping pattern has has been shattered since lockdown has been in effect)…