简体   繁体   中英

How to write a function that takes an Array of strings as an argument and prints the first letter of each element out (one per line)

I am working on my first javascript assignment and we have been asked to "Write a function that takes an Array of strings as an argument and prints the first letter of each element out (one per line)" however we must use a FOR OF loop, function, and charAt() the output should be HWTIMS each letter on its own line I am struggling because I only know how to complete the task by using the toString.charAt method but that is not what the assignment asked for. I also am not sure if the for of loop goes in the function or the function goes in the loop. Just started JS last week very confused. Please help.

let arr = (["Hello", "World", "This", "Is", "My", "String"]);
//  required for of
for (let element of arr) {
    console.log(element.toString())
}
 



// required function
let myFunction = (element) => element.charAt(0);

 myFunction(arr)
 

// required charAt
var str = new String( "This is string" );

        
         console.log( arr.toString().charAt(0));
         console.log(  arr.toString().charAt(6));
         console.log(  arr.toString().charAt(12));
         console.log(  arr.toString().charAt(17));
         console.log(  arr.toString().charAt(20));
         console.log( arr.toString().charAt(23));

See below four examples, the first one is your answer, they are loops.

 let arr = (["Hello", "World", "This", "Is", "My", "String"]); let myFunction = element => console.log(element.charAt(0)); console.log('\nfor of mode'); for (const iterator of arr) { myFunction(iterator); } console.log('\nfor each mode'); arr.forEach(element => { myFunction(element); }); console.log('\nfor each mode2'); arr.forEach( el => myFunction(el) ); console.log('\nfor mode'); for (let index = 0; index < arr.length; index++) { const element = arr[index]; myFunction(element); }

Use this expression on each loop:

 // word is a string from the array of strings word.toString().charAt(0)+'\n'

Details are commented in example below

 let hwtims = ["Hello", "World", "This", "Is", "My", "String"]; /* Declare new string outside of loop: let char = '' On each loop add to char: += Get the first character of each word: .toString().charAt(0) Add a newline: +'\n' */ const firstChar = array => { let char = ''; for (let word of array) { char += word.toString().charAt(0) + '\n'; } return char; }; console.log(firstChar(hwtims));

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