【发布时间】:2021-08-04 01:04:37
【问题描述】:
正在学习 JavaScript,目前在迭代器中做一个项目来“lint”一个包含文本故事的数组。 Linting 是指从某种形式的写作中编辑/过滤掉单词或语法的过程。
我的问题 - 目前我可以将其用于 .filter overusedWords,但我想保存一个单词的使用次数并返回该数量,例如:(“你使用了 ${overusedWords} X 次”)。但是,它只会打印我正在过滤的单词,无论它出现多少次。
我尝试在这个迭代器循环内部/外部定义字计数器。现在我正在尝试将该部分重写为 'if (overused.filter(word => { === 'example'}) type
该项目是为了习惯 .(iterator) 方法,因此解决方案应该围绕使用它展开。希望你能帮助我解决这个问题并更好地学习:)
let word1 = 0;
let word2 = 0;
let word3 = 0;
const countOverUsed = betterWords.filter((word, word1, word2, word3) => {
if (word === 'really') {
word1 = word1 + 1;
return word1;
} else if (word === 'very') {
word2 = word2 + 1;
return word2;
} else if (word === 'basically') {
word3 = word3 + 1;
return word3;
}
});
console.log(countOverUsed);
整个项目
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 overusedWords = ['really', 'very', 'basically'];
let unnecessaryWords = ['extremely', 'literally', 'actually' ];
const storyWords = story.split(' ');
console.log(storyWords.length);
const betterWords = storyWords.filter(function(element) {
if (unnecessaryWords.includes(element)) {
console.log(element)
} else {
return element;
}
});
let word1 = 0;
let word2 = 0;
let word3 = 0;
const countOverUsed = betterWords.filter((word, word1, word2, word3) => {
if (word === 'really') {
word1 = word1 + 1;
return word1;
} else if (word === 'very') {
word2 = word2 + 1;
return word2;
} else if (word === 'basically') {
word3 = word3 + 1;
return word3;
}
});
console.log(countOverUsed);
【问题讨论】:
标签: javascript arrays iterator filtering