为什么“返回”不返回任何东西(JS)

我写了一个关于在单词中查找元音的代码。感谢console.log,我得到了输出,它可以工作。但是一旦我尝试返回,它不会返回任何东西..我不明白为什么?


这里的代码:


function vowelCount(str) {

  let word = str.split("");

  //   console.log(word);

  //   console.log(word.length - 1);

  let count = 0;

  for (let i = 0; i <= word.length - 1; i++) {

    if (

      str[i] === "a" ||

      str[i] === "e" ||

      str[i] === "i" ||

      str[i] === "o" ||

      str[i] === "u" ||

      str[i] === "y"

    ) {

      count = count + 1;

    }

  }

  //   console.log(count);

  return count;

}


vowelCount("hello");

vowelCount("thereactor");


倚天杖
浏览 168回答 4
4回答

跃然一笑

它正在回归。您只是没有使用返回值。这可以通过以下方式确定:console.log(vowelCount("hello"));

慕斯709654

确保使用返回的数据。var vowelsInHello = vowelCount("hello");console.log(vowelsInHello);

拉风的咖菲猫

您的代码返回一个值。也许你没有调用这个函数。注意:使用字符串调用函数,例如:console.log("hello world");

白衣非少年

这是一个更好的方法function vowelCount(str) {&nbsp; &nbsp; let count = 0;&nbsp; &nbsp; for (let i = 0; i <= str.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var char = str.charAt(i).toLowerCase()&nbsp; &nbsp; &nbsp; &nbsp; if (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char === "a" ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char === "e" ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char === "i" ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char === "o" ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char === "u" ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char === "y"&nbsp; &nbsp; &nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return count;}console.log(vowelCount('this has some vowels'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript