【问题标题】:JS How to create a function that count the number of hashtagsJS 如何创建一个计算标签数量的函数
【发布时间】:2018-12-24 15:26:54
【问题描述】:

此问题已被删除

【问题讨论】:

  • let hashTagCount = "很高兴能在周一开始@coding!#learntocode #codingbootcamp".split("#").length - 1; , 你能用这个检查一下吗
  • 同样你也可以检查mentionCount。
  • 做一些基本的调试。您甚至没有尝试创建预期的对象。如果不熟悉如何使用控制台日志记录,现在是学习的好时机。大量的资源和教程来学习基本的调试方法

标签: javascript loops count numbers


【解决方案1】:

一个简单的循环就可以了。由于您使用的是 ES2015+ 语法,因此 for-of 会很好地工作:

function countHashtagsAndMentions(str) {
  let hashtags = 0;
  let mentions = 0;
  for (const ch of str) {
    if (ch === "#") {
      ++hashtags;
    } else if (ch === "@") {
      ++mentions;
    }
  }
  return {hashtags, mentions};
}
let str = "So excited to start  @coding on Monday! #learntocode #codingbootcamp";
console.log(countHashtagsAndMentions(str));

这是因为字符串在 ES2015+ 中是 iterablefor-of loop 隐式使用字符串中的迭代器来遍历其字符。所以在循环中,ch 是字符串中的每个字符。请注意,与str.split() 不同,字符串迭代器不会将需要代理对的字符的两半分开(就像大多数表情符号一样),这通常是您想要的。

这个:

for (const ch of str) {
    // ...
}

实际上与

相同
let it = str[Symbol.iterator]();
let rec;
while (!(rec = it.next()).done) {
    const ch = rec.value;
    // ...
}

但没有 itrec 变量。


或者,您可以使用带有正则表达式的replace 来替换除您要计算的字符之外的所有字符。听起来会更贵,但这是 JavaScript 引擎可以优化的:

function countHashtagsAndMentions(str) {
  return {
    hashtags: str.replace(/[^#]/g, "").length,
    mentions: str.replace(/[^@]/g, "").length
  };
}
let str = "So excited to start  @coding on Monday! #learntocode #codingbootcamp";
console.log(countHashtagsAndMentions(str));

您使用哪个可能部分取决于字符串的长度。 replace 选项又好又短,但确实会遍历字符串两次。

【讨论】:

  • 谢谢你这工作完美。我对for (const ch of str) 有疑问。你能解释一下这是如何工作的吗?我从来没有使用过这样的 for 循环。
  • @GeorgiaLumley - 我已经更新了部分答案,并提供了一些链接供进一步阅读。编码愉快!
  • 非常感谢。
【解决方案2】:

您可以使用一个对象进行检查和计数。

function countHashtagsAndMentions(str) {
    var result = { '#': 0, '@': 0 },
        i;

    for (i = 0; i < str.length; i++) {
        if (str[i] in result) ++result[str[i]];
    }
    return result;
}

var str = "So excited to start  @coding on Monday! #learntocode #codingbootcamp";

console.log(countHashtagsAndMentions(str));

【讨论】:

    【解决方案3】:

    使用数组#reduce

    const message = "So excited to start @coding on Monday! #learntocode #codingbootcamp"
    
    const res = message.split("").reduce((acc,cur)=>{
      
      if('#@'.includes(cur)){
        const key = cur === '#' ? 'hashtags' : 'mentions';
        acc[key] = acc[key] + 1;
    
      }
      
      return acc;
    }, {mentions: 0, hashtags: 0})
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      相关资源
      最近更新 更多