美文网首页
#169 JavaScript Iterators

#169 JavaScript Iterators

作者: 钤鱼摆摆 | 来源:发表于2018-01-30 07:10 被阅读0次

    This is an article with the notes that I summarized after learning「Introduction To JavaScript」in Codecademy.

    Iterators

    Iterators are methods that are called on arrays and complete tasks of looping through the arrays.

    .forEach() method
    let fruits = ['mango', 'apple', 'pineapple', 'banana'];
    
    // Iterate over fruits 
    fruits.forEach(fruit => console.log("I want to eat a " + fruit));
    
    // expected outputs:
    // I want to eat a mango
    // I want to eat a apple
    // I want to eat a pineapple
    // I want to eat a banana
    

    In this method .forEach() iterates through the whole list fruits, and each time it iterates an item, it will log the sentence I want to eat a fruit into the console.

    .map() method
    let words = ['Hey', 'elephant', 'listen', 'list', 'old', 
                 'What', 'octopus', 'rabbit', 'lie', 'deep'];
    
    // iterates through each word
    // and changes the word to the new returned word
    let secretMessage = words.map(word => word[0]);
    
    console.log(secretMessage.join('');
    // HelloWorld
    

    This method is similar to the former method, it still can iterates through the whole list. The difference is that each time it iterates through a word, the new returned word will replace the original word. In this case the returned word is word[0], which is the first letter of each word. So after the complete iteration, the list words will become ['H', 'e', 'l', 'l, 'o', 'W', 'o', 'r', 'l', 'd']. And with the method .join(''), all the items in the list will be joined into a single string HelloWorld.

    .filter() method
    let favoriteFood = ['tempeh', 'strawberry', 'orange', 'bread', 'cereal'];
    
    let longFavoriteFood = favoriteFood.filter(food => food.length > 5);
    // filters out all words that have length smaller than or equal to 5
    
    console.log(longFavoriteFood);
    // ['tempeh', 'strawberry', 'orange', 'cereal']
    

    This method is used to filter an array. In this example, each time it loops through an item, it will look at the length property of that item. If its length is smaller than or equal to 5, this item will be filtered out. In this end, only the items that have length bigger than 5 will be returned.

    相关文章

      网友评论

          本文标题:#169 JavaScript Iterators

          本文链接:https://www.haomeiwen.com/subject/qttqzxtx.html