[英]JS How to create a function that count the number of hashtags
此問題已被刪除
一個簡單的循環就可以了。 由於您使用的是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 +中是可迭代的 。 for-of
循環隱式使用字符串中的迭代器來遍歷其字符。 所以在循環中, ch
是字符串中的每個字符。 請注意,與str.split()
不同,字符串迭代器不會分別代表需要代理對的字符的兩半(如大多數表情符號),這通常是您想要的。
這個:
for (const ch of str) {
// ...
}
實際上是一樣的
let it = str[Symbol.iterator]();
let rec;
while (!(rec = it.next()).done) {
const ch = rec.value;
// ...
}
但沒有it
和rec
變量。
或者,您可以使用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
選項很好而且很短,但確實會經過兩次字符串。
您可以使用對象進行檢查和計數。
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));
使用Array#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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.