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

Ran*_*Dad 3 javascript

我的代码中遗漏了什么吗?它似乎只抓取第一个字母,而 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
}
Run Code Online (Sandbox Code Playgroud)

小智 5

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

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

console.log(acronym('three letter acronym'));
Run Code Online (Sandbox Code Playgroud)

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

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

console.log(acronym('three letter acronym'));
Run Code Online (Sandbox Code Playgroud)


Dav*_*mas 3

将分隔符添加到split

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
}
Run Code Online (Sandbox Code Playgroud)

JS 小提琴演示

修改了上面的内容,使其更具演示性,也更具互动性:JS Fiddle demo


编辑添加参考和解释:

因为没有提供分隔符,所以字符串保持未分割状态;因此while操作正确(等于words.length1,因此仅返回字符串的第一个字母:

[Separator] 指定用于分隔字符串的字符。分隔符被视为字符串或正则表达式。如果省略分隔符,则返回的数组包含一个由整个字符串组成的元素。

参考: