gpt4 book ai didi

javascript - JavaScript 中的首字母缩略词生成器。它只抓取第一个单词的第一个字母,而不抓取其他单词

转载 作者:行者123 更新时间:2023-11-30 07:46:00 24 4
gpt4 key购买 nike

我的代码中是否遗漏了什么?它似乎只捕获第一个字母,而 while 循环不会进入下一个单词。那么我可能会遗漏什么?

function acr(s){
var words, acronym, nextWord;

words = s.split();
acronym= "";
index = 0
while (index<words.length) {
nextWord = words[index];
acronym = acronym + nextWord.charAt(0);
index = index + 1 ;
}
return acronym
}

最佳答案

如果您只关心 IE9+,那么答案可以更短:

function acronym(text) {
return text
.split(/\s/)
.reduce(function(accumulator, word) {
return accumulator + word.charAt(0);
}, '');
}

console.log(acronym('three letter acronym'));

如果你可以使用箭头函数,那么它还可以变得更短:

function acronym(text) {
return text
.split(/\s/)
.reduce((accumulator, word) => accumulator + word.charAt(0), '');
}

console.log(acronym('three letter acronym'));

关于javascript - JavaScript 中的首字母缩略词生成器。它只抓取第一个单词的第一个字母,而不抓取其他单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6145218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com