我在代码中缺少什么吗?似乎只捕获第一个字母,而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'));

09-11 06:54