[英]How to loop through string, adding 1 extra character to an array each time
[英]How to loop through an array to get the first character of each string
我正在提取單詞的第一個字母以形成首字母縮寫詞。 我有一個數組來存儲所有大寫的單詞,我需要做的就是獲取那些大寫的字符。
我使用了數組reduce()
方法來獲取大寫字母。 但是,我想獲得由不同大小寫字母組成的所有首字母縮寫詞。
var words = ["In", "American", "Broadcast", "Company"];
var output = words.reduce((acronym, word) => {
acronym += word.charAt(0);
return acronym;
}, "");
這將產生一個輸出IABC
,但是我們知道正確的首字母縮寫是ABC
,所以我想我們可以迭代獲得C, BC, ABC, IABC
,然后獲得正確的首字母縮寫ABC
嗎?
為了獲得預期的結果,請使用以下反轉數組選項,並使用帶有未移位數組的reduce方法
工作代碼示例以供參考
var words = ["In", "American", "Broadcast", "Company"]; var result = [] var output = words.reverse().reduce((acronym, word, i) => { acronym.unshift(word.charAt(0)) result.push(acronym.join("")) return acronym; }, []); console.log("result", result);
codepen- https: //codepen.io/nagasai/pen/voXXYO ? editors = 1010
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.