为了账号安全,请及时绑定邮箱和手机立即绑定

计算字符串中的单词

计算字符串中的单词

九州编程 2019-12-25 15:43:57
function WordCount(str) {  var totalSoFar = 0;  for (var i = 0; i < WordCount.length; i++)    if (str(i) === " ") { // if a space is found in str      totalSoFar = +1; // add 1 to total so far  }  totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words}console.log(WordCount("Random String"));我认为我已经很好地理解了这一点,除了我认为if陈述是错误的。怎么说if(str(i)包含空格,加1。编辑:我发现(感谢Blender)可以用更少的代码来做到这一点:function WordCount(str) {   return str.split(" ").length;}console.log(WordCount("hello world"));
查看完整描述

3 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

使用方括号,而不是括号:


str[i] === " "

或charAt:


str.charAt(i) === " "

您也可以使用.split():


return str.split(' ').length;


查看完整回答
反对 回复 2019-12-25
  • 3 回答
  • 0 关注
  • 349 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信