[英]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.