开发者问题收集

使用 JavaScript 迭代器的困难

2018-01-05
79

希望你今天过得很愉快。我无法使用迭代器获得预期结果。我查看了有关迭代器的 MDN 文档,我觉得我理解如何使用它们,但我可能搞错了,因为我对编码还很陌生。

以下是我的代码:

    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"];

let storyWords = story.split("");

console.log(storyWords.length);

let betterWords = storyWords.filter(function(word) {
  if (!unnecessaryWords.includes(word)) {
    return word;
  }
});

console.log(betterWords);

let totalUsed = 0;

for (let i = 0; i < betterWords.length; i++){
    if (betterWords[i] === overusedWords[0]) {
      totalUsed++;
    } else if (betterWords[i] === overusedWords[1]) {
        totalUsed++;
    } else if (betterWords[i] === overusedWords[2]) {
        totalUsed++;
    }
  }

第一个预期结果 - console.log(betterWords) 语句应打印出不包含 unwantedWords 中列出的单词的故事。

第二个预期结果 - console.log(totalUsed) 语句应打印出这些单词在故事中出现的总次数。

目前,我从 console.log 语句中分别获得了 978 和 0。

任何帮助都非常感谢!

3个回答

几件事:

  • 您应该用空格分割故事字符串: " " ,而不是用空字符串来获取字数。用空字符串分割: "" ,将为您提供一个包含每个字符而不是每个单词的数组。
  • 数组 .filter 方法采用应返回布尔值的函数。如果该布尔值为真,则保留该项目,否则将其删除。因此,如果它是一个不必要的单词,您的过滤器将返回该单词,但这是真的,所以您实际上只会保留不必要的单词。最好直接返回 .includes 调用的结果。
  • 最后,用于计算过度使用单词的 for 循环应该可以完美运行,但您也可以使用数组 .reduce 方法,因为它基本上非常适合该用例。
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"];

// First, empty string split will separate the story into each individual character,
// when you want to get each word. To do that, split on a space character:
let storyWords = story.split(" ");
console.log("Story word count:", storyWords.length);

// In ES6, you can use an arrow function which is more concise. Also, the filter method
// should return a boolean. Your filter returns either the word itself (truthy) or
// undefined (falsey), and filter keeps the items we return true for, so your filter was
// actually keeping ONLY the unnecessaryWords.
let betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));
console.log("A better story word count:", betterWords.length);
console.log("A better story:\n\n", betterWords.join(" "));

// For total used, this is the perfect place for a reduce:
let totalUsed = betterWords.reduce((count, word) => {
    if (overusedWords.includes(word)) count++;
    return count;
}, 0);

console.log("Total used:", totalUsed);
CRice
2018-01-05

这里有几件事要做。正如其他人指出的那样, split 不是您所需要的。

我建议这样做:

let storyWords = story.split(/\W+/);

按非单词字符进行拆分解决了标点符号问题以及空格问题。这将有助于在按空格拆分可能会给您一个停用词(包括标点符号,如“really.”,如果它位于句子末尾)的情况。它并不完美 — 例如缩写将被拆分。如果您想改进它,请查看标记化的建议;在所有情况下都很难正确执行。

此外, filter() 接受布尔值,而 includes() 返回布尔值,因此您可以使用类似以下内容简化过滤器语句:

let betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));

并且您也可以在最后的计数循环中使用 includes,如果您添加更多停用词,它将更加灵活:

for (let i = 0; i < betterWords.length; i++){
  if (overusedWords.includes(betterWords[i])) {
    totalUsed++;
  }
}

这也可以使用 reduce() 简化:

let totalUsed = betterWords.reduce((a, c) => overusedWords.includes(c) ? a + 1 : a, 0)
Mark
2018-01-05

这可能是一个细节,但快速浏览一下,我可以看到您的拆分目前正在获取每个字符。 您可能想要执行类似这样的操作:

let str = "How are you doing today?";
let res = str.split(" ");

这给出了这个数组:

[How,are,you,doing,today?]

我想这是一个开始:P

Jean-Philippe Bergeron
2018-01-05