难以使用JavaScript迭代器

时间:2018-01-05 21:24:34

标签: javascript arrays iterator

希望你过得愉快。我的迭代器无法获得预期的结果。我查看了关于迭代器的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)语句应该打印出没有不必要词语中列出的单词的故事。

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

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

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:1)

一些事情:

  • 您应该将故事字符串拆分为空格:" ",而不是空字符串以获取字数。拆分空字符串:"",将为每个字符提供一个数组,而不是每个字。
  • 数组.filter方法接受一个应返回布尔值的函数。如果该布尔值为true,则保留该项,否则将其删除。所以如果你的过滤器是一个不必要的单词,那么你的过滤器就会返回这个单词,但这样做真的很糟糕,所以你实际上只会保留不必要的单词。最好直接返回.includes来电的结果。
  • 最后,您的for循环计算过度使用的单词应该可以正常工作,但您也可以使用数组.reduce方法,因为它基本上非常适合该用例。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你在这里有几件事。其他人指出的split并不是你所需要的。

我会建议像:

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

这对非单词字符的拆分解决了标点符号问题以及空格问题。这将有助于分割空间可能会给你一个停顿词,包括标点符号,例如“真实”。如果它在句子的末尾。它并不完美 - 例如宫缩会分裂。如果你想改进它,请查看令牌化的建议;对所有情况都很难做到正确。

此外,filter()采用布尔值,includes()返回布尔值,因此您可以使用以下内容简化filter语句:

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

你也可以在最后使用包含循环计数循环,如果你添加更多停用词,它会更灵活:

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)

答案 2 :(得分:0)

这可能是一个细节,但通过快速浏览,我可以看到你的分裂正在获得每个字符。 你可能想做类似的事情:

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

这给出了这个数组:

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

这是一个开始我猜:P

答案 3 :(得分:0)

将要删除/计数的单词数组转换为单词边界分隔单词列表的正则表达式。

  1. String#replace与表达式一起使用以删除单词。

  2. String#match与表达式一起使用以获取已删除单词的数组。数组的长度为totalUsed

  3. &#13;
    &#13;
    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 unnecessaryWords = ["extremely", "literally", "actually"];
    const unRegExp = new RegExp(`\\b${unnecessaryWords.join('|')}\\b`, 'gi');
    const betterWords = story.replace(unRegExp, '');
    console.log(betterWords);
    
    const overusedWords = ["really", "very", "basically"];
    const overRegExp = new RegExp(`\\b${overusedWords.join('|')}\\b`, 'gi');
    const totalUsed = (story.match(overRegExp) || []).length;
    console.log(`total overused used:`, totalUsed);
    &#13;
    &#13;
    &#13;