我对javascript很陌生,还在学习一些数据类型,我得到了一些我无法理解的内容,请帮助我。
练习问题:
“爱是这个世界上最好的东西。有些人找到了他们的爱,有些人仍然在寻找他们的爱。”数一数这个句子中这个词的个数。
所以我尝试了一些基本的方法,比如,
我数不清爱和给予爱的词的索引。
我如何编码这个以找到答案?
发布于 2022-02-27 15:42:37
这应该能行。
let sentence = "Love is the best thing in this world.
Some found their love and some are still looking for their love."
console.log(sentence.split("love").length)发布于 2022-02-27 15:42:54
这应该能行
const sentence = 'Love is the best thing in this world. Some found their love and some are still looking for their love.'
const occurrences = sentence.match(/love/gi); // (g is is for match all occurrences, i is for case insensitive)
console.log("number of occurrences of 'love'", occurrences.length)发布于 2022-02-27 15:55:06
为了使它更加通用,并显示使用了reduce:
const data = "Love is the best thing in this world. Some found their love and some are still looking for their love"
const dataArray = data.split(' ');
const wordMap = dataArray.reduce((result, word) => {
result[word.toLowerCase() ]= result[word.toLowerCase() ] ? result[word] + 1 : 1;
return result
}, {});
console.log(wordMap["love"])
console.log(wordMap["is"])
console.log(wordMap["best"])
https://stackoverflow.com/questions/71286099
复制相似问题