JS - callbacks & array methods

refer to: https://www.udemy.com/course/the-web-developer-bootcamp/

  • for each, 逐个遍历元素, 相当于 for……of , The forEach() method executes a provided function once for each array element.
  • const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    
    numbers.forEach(function (el) {
        if (el % 2 === 0) {
            console.log(el)
        }
    })
    
    // for (let el of numbers) {
    //     console.log(el);
    // }
    
    const movies = [
        {
            title: 'Amadeus',
            score: 99
        },
        {
            title: 'Stand By Me',
            score: 85
        },
        {
            title: 'Parasite',
            score: 95
        },
        {
            title: 'Alien',
            score: 90
        }
    ]
    
    movies.forEach(function (movie) {
        console.log(`${movie.title} - ${movie.score}/100`)
    })
  • map,  The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
  • const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    
    const doubles = numbers.map(function (num) {
        return num * 2;
    })
    
    
    const movies = [
        {
            title: 'Amadeus',
            score: 99
        },
        {
            title: 'Stand By Me',
            score: 85
        },
        {
            title: 'Parasite',
            score: 95
        },
        {
            title: 'Alien',
            score: 90
        }
    ]
    
    const titles = movies.map(function (movie) {
        return movie.title.toUpperCase();
    })
  • arrow functions, "(a,b)=>"替代"function(a,b)"
    • =>后直接接(xxx) == =>后接{return xxx}, 花括号要写return,小括号可以省略return。
    • 一行代码的时候小括号也可以省略
  • // const add = function(x,y) {
    //     return x + y;
    // }
    
    // const add = (x, y) => {
    //     return x + y;
    // }
    
    const add = (a, b) => a + b;
    
    
    const square = num => {
        return num * num;
    }
    
    // const rollDie = () => {
    //     return Math.floor(Math.random() * 6) + 1
    // }
    
    const rollDie = () => (
        Math.floor(Math.random() * 6) + 1
    )
    
    
    
    
    const movies = [
        {
            title: 'Amadeus',
            score: 99
        },
        {
            title: 'Stand By Me',
            score: 85
        },
        {
            title: 'Parasite',
            score: 95
        },
        {
            title: 'Alien',
            score: 90
        }
    ]
    
    // const newMovies = movies.map(function (movie) {
    //     return `${movie.title} - ${movie.score / 10}`
    // })
    
    
    // IMPLICIT RETURN
    const newMovies = movies.map(movie => (
        `${movie.title} - ${movie.score / 10}`
    ))

     

  • filter, filter elements in order to satisfy some specific conditions. The filter() method creates a new array with all elements that pass the test implemented by the provided function.
  • const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    
    numbers.filter(n => {
        return n < 10
    })
    
    
    const movies = [
        {
            title: 'Amadeus',
            score: 99,
            year: 1984
        },
        {
            title: 'Sharknado',
            score: 35,
            year: 2013
        },
        {
            title: '13 Going On 30',
            score: 70,
            year: 2004
        },
        {
            title: 'Stand By Me',
            score: 85,
            year: 1986
        },
        {
            title: 'Waterworld',
            score: 62,
            year: 1995
        },
        {
            title: 'Jingle All The Way',
            score: 71,
            year: 1996
        },
        {
            title: 'Parasite',
            score: 95,
            year: 2019
        },
        {
            title: 'Notting Hill',
            score: 77,
            year: 1999
        },
        {
            title: 'Alien',
            score: 90,
            year: 1979
        }
    ]
    
    
    
    const badMovies = movies.filter(m => m.score < 70)
    
    const recentMovies = movies.filter(m => m.year > 2000)
    
    // const goodMovies = movies.filter(m => m.score > 80)
    // const goodTitles = goodMovies.map(m => m.title)
    
    movies.filter(m => m.score > 80).map(m => m.title);
  • some & every, 返回值是布尔型
    • some,至少有一个符合指定条件的时候返回true.
    • every, 所有元素都符合指定条件的时候返回true.
  • const exams = [80, 98, 92, 78, 77, 90, 89, 84, 81, 77]
    
    exams.every(score => score >= 75)
    
    const movies = [
        {
            title: 'Amadeus',
            score: 99,
            year: 1984
        },
        {
            title: 'Sharknado',
            score: 35,
            year: 2013
        },
        {
            title: '13 Going On 30',
            score: 70,
            year: 2004
        },
        {
            title: 'Stand By Me',
            score: 85,
            year: 1986
        },
        {
            title: 'Waterworld',
            score: 62,
            year: 1995
        },
        {
            title: 'Jingle All The Way',
            score: 71,
            year: 1996
        },
        {
            title: 'Parasite',
            score: 95,
            year: 2010
        },
        {
            title: 'Notting Hill',
            score: 77,
            year: 1999
        },
        {
            title: 'Alien',
            score: 90,
            year: 1979
        }
    ]
    
    
    movies.some(movie => movie.year > 2015)
  • setTimeout && clearTimeout and setInterval && clearInterval
    • The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout()) sets a timer which executes a function or specified piece of code once the timer expires.
    • The clearTimeout() method of the WindowOrWorkerGlobalScope mixin cancels a timeout previously established by calling setTimeout().
    • The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval(). This method is defined by the WindowOrWorkerGlobalScope mixin.
  • console.log("HELLO!!!...")
    setTimeout(() => {
        console.log("...are you still there?")
    }, 3000) //3000milliseconds delay,调用function之前的delay
    
    console.log("GOODBYE!!")
    
    
    const id = setInterval(() => {
        console.log(Math.random())
    }, 2000);  //2000milliseconds delay, 重复调用一个function的delay
    
    

     // clearInterval(id);

  • reduce
    • The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
  • const prices = [9.99, 1.50, 19.99, 49.99, 30.50];
    
    // let total = 0;
    // for (let price of prices) {
    //     total += price
    // }
    // console.log(total)
    
    // const total = prices.reduce((total, price) => {
    //     return total + price
    // }) //累加,求和
    
    const total = prices.reduce((total, price) => total + price)
    
    const minPrice = prices.reduce((min, price) => {
        if (price < min) {
            return price;
        }
        return min;
    })  //求最值
    
    const movies = [
        {
            title: 'Amadeus',
            score: 99,
            year: 1984
        },
        {
            title: 'Sharknado',
            score: 35,
            year: 2013
        },
        {
            title: '13 Going On 30',
            score: 70,
            year: 2004
        },
        {
            title: 'Stand By Me',
            score: 85,
            year: 1986
        },
        {
            title: 'Waterworld',
            score: 62,
            year: 1995
        },
        {
            title: 'Jingle All The Way',
            score: 71,
            year: 1996
        },
        {
            title: 'Parasite',
            score: 95,
            year: 2019
        },
        {
            title: 'Notting Hill',
            score: 77,
            year: 1999
        },
        {
            title: 'Alien',
            score: 90,
            year: 1979
        }
    ]
    
    const highestRated = movies.reduce((bestMovie, currMovie) => {
        if (currMovie.score > bestMovie.score) {
            return currMovie;
        }
        return bestMovie;
    })
    
    
    // We can provide an initial value as the 2nd arg to reduce: 设置第二个参数为一个定值
    const evens = [2, 4, 6, 8];
    evens.reduce((sum, num) => sum + num) //20
    evens.reduce((sum, num) => sum + num, 100) //120
  • arrowFunctions this
  • const person = {
        firstName: 'Viggo',
        lastName: 'Mortensen',
        fullName: function () {
            return `${this.firstName} ${this.lastName}`
        },
        shoutName: function () {
            setTimeout(() => {
                //keyword 'this' in arrow functions refers to the value of 'this' when the function is created
                console.log(this);
                console.log(this.fullName())
            }, 3000)
        }
    }

 

上一篇:Html之有意思的javascript 的 “BUG”


下一篇:vue组件间通信