任务:
有一系列单词,称为overusedWords。这些是这个故事中过度使用的词。您想让程序用户知道他们使用了这些过度使用的单词的次数。有两种方法可以实现此目的。首先自己尝试。如果需要帮助,请查阅提示。
提示:
1。您可以迭代遍历BetterWords数组三个不同的时间(对overusedWords数组中的每个单词一次)。创建一个代表单词出现的总次数的变量。每当当前单词与该单词相同时,在变量中加1。
2。您可以通过在迭代器的功能代码块中使用一个if和两个else if语句来简化此操作。这样,您可以一次收集所有三个过度使用的单词的计数。
代码:
> :kind Either
Either :: * -> * -> *
> :kind Either String
Either String :: * -> *
> :kind Either String Int
Either String Int :: *
> :kind []
[] :: * -> *
> :kind [] Int
[] Int :: *
> :kind [Int]
[Int] :: *
> :kind Functor
Functor :: (* -> *) -> Constraint
> :kind Num
Num :: * -> Constraint
答案 0 :(得分:0)
您可以定义自己的函数以充当过滤器。例如,如果给我一个年龄段,并且只想返回20至35岁之间的年龄,则可以执行以下操作:
var ages = [32, 33, 16, 40];
console.log(ages.filter(checkAge));
function checkAge(age) {
if (age > 20 && age < 35) {
return age;
}
}
这将返回以下输出:
Array [ 32, 33 ]
答案 1 :(得分:0)
使用Array.prototype.reduce()
和单个if
怎么办?
const story = `Last weekend, I took literally the most beautiful bike ride of
my life. The route is called "The 9W to Nyack" and it actually stretches
all the way from Riverside Park in Manhattan to South Nyack, New Jersey.
It\'s really an adventure from beginning to end! It is a 48 mile loop and
it basically took me an entire day. I stopped at Riverbank State Park to
take some extremely artsy photos. It was a short stop, though, because I
had a really long way left to go. After a quick photo op at the very
popular Little Red Lighthouse, I began my trek across the George
Washington Bridge into New Jersey. The GW is actually very long - 4,760
feet! I was already very tired by the time I got to the other side. An
hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful
park along the coast of the Hudson. Something that was very surprising
to me was that near the end of the route you actually cross back into New
York! At this point, you are very close to the end.`;
const storyWords = story.toLowerCase().split(' ');
const overusedWords = ['really', 'very', 'basically'];
const results = storyWords.reduce((acc, word) => {
if (overusedWords.includes(word)) {
acc[word] = (acc[word] || 0) + 1;
}
return acc;
}, {});
console.log(results)
如本例所示,您也可以在filter()
/ reduce()
之外的某个时间致电String.prototype.toLowerCase()
。
如果您仍然喜欢使用filter()
,则上面的示例应该很容易适应,因此我将留给您。