【发布时间】:2018-12-17 18:35:52
【问题描述】:
任务:
有一个单词数组叫做 overusedWords。这些是这个故事中过度使用的词。你想让你的程序的用户知道他们使用了多少次这些过度使用的词。有两种方法可以实现这一点。先自己试试吧。如果您需要帮助,请查阅提示。
提示:
1.您可以对 betterWords 数组进行三次单独的迭代(对 overusedWords 数组中的每个单词执行一次)。创建一个变量,表示该单词出现的总次数。每次当前单词与该单词相同时,变量加 1。
2.您可以通过在迭代器的函数代码块中使用一个 if 和两个 else if 语句来简化此操作。这样,您可以一次收集所有三个过度使用的单词的计数。
代码:
let 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.';
let storyWords = story.split(' ')
console.log(storyWords)
console.log(storyWords.length)
let overusedWords = ['really', 'very', 'basically'];
let unnecessaryWords = ['extremely', 'literally', 'actually' ];
let betterWords = storyWords.filter( storyWords =>
!unnecessaryWords.includes(storyWords.toLowerCase()));
console.log(betterWords)
【问题讨论】:
-
我投票决定将此问题作为离题结束,因为它看起来像家庭作业,并且 看不到 OP 的任何努力。
-
查看this answer 获取有关如何寻求家庭作业帮助的一些指导。
-
回答标题中的问题:您可以在
filter中使用if。filter接受一个函数;在经典的function(arg) { ... }函数中,显然可以使用if。您使用的箭头函数有两种形式:表达式形式arg => expr和块形式arg => { ... }。不能在表达式中使用if,但可以使用三元运算符。您可以在块内使用if。
标签: javascript if-statement iterator