[英]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.我正在处理我的第一个 javascript 作业,我们被要求“编写一个 function,它将字符串数组作为参数并打印出每个元素的第一个字母(每行一个)”但是我们必须使用 FOR OF 循环, function 和 charAt() output 应该是 HWTIMS 每个字母都在自己的行中 我正在苦苦挣扎,因为我只知道如何使用 toString.charAt 方法完成任务,但这不是作业要求的。 I also am not sure if the for of loop goes in the function or the function goes in the loop.
我也不确定 for of 循环是否进入 function 或 function 进入循环。 Just started JS last week very confused.
上周刚开始JS很迷茫。 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.