我是编码新手,需要回答这个问题。
这个问题是;
创建一个函数来接收一个字符串,该字符串将包含 Twitter 上的许多提及和主题标签。
E.g. "So excited to start @coding on Monday! #learntocode #codingbootcamp"
该函数应返回一个对象,描述找到的主题标签和提及的数量:
{ hashtags: 2, mentions: 1 }
我创建的代码是这样的;
function countHashtagsAndMentions(str) {
let split = str.split(" ");
let count = 0
for (let i = 9; i < str.length; i++) {
let hash = split.filter(hashtag => hashtag.match(/#/g))
if (hash === 1) {
count ++
}
let total = {
hash = count,
}
return hash
}
}
我的代码正在针对此运行;
describe("countHashtagsAndMentions", () => {
it("returns an object", () => {
expect(typeof countHashtagsAndMentions("")).to.equal("object");
});
it("returns {hashtags: 0, mentions: 0} if it finds none", () => {
expect(
countHashtagsAndMentions(
"hello this is a tweet guaranteed to get very little engagement"
)
).to.eql({ hashtags: 0, mentions: 0 });
});
it("recognises no mentions", () => {
expect(countHashtagsAndMentions("#yolo")).to.eql({
hashtags: 1,
mentions: 0
});
});
it("recognises no hashtags", () => {
expect(countHashtagsAndMentions("@yobo")).to.eql({
hashtags: 0,
mentions: 1
});
});
it("finds multiple hashtags and mentions and returns that number", () => {
expect(countHashtagsAndMentions("#yolo @bolo #golo")).to.eql({
hashtags: 2,
mentions: 1
});
expect(countHashtagsAndMentions("@boyo #goyo @loyo #zoyo")).to.eql({
hashtags: 2,
mentions: 2
});
expect(
countHashtagsAndMentions(
'"So excited to start at @northcoders on Monday! #learntocode #codingbootcamp"'
)
).to.eql({ hashtags: 2, mentions: 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));
这是可行的,因为字符串是 iterable在 ES2015+ 中。 for-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;
// ...
}
但没有 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
选项很好而且很短,但确实会遍历字符串两次。
关于javascript - JS如何创建一个计算主题标签数量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915202/