zoukankan      html  css  js  c++  java
  • Newer js features

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


    • default parameters, 默认参数放在最后面
    • function multiply(a, b = 1) {
          return a * b;
      }
      multiply(3); //3
      
      function multiply(a = 1, b) {
          return a * b;
      }
      multiply(3); //NaN
      // ==========================================
      // AN OLDER WAY OF ADDING DEFAULT PARAM VALUE
      // ==========================================
      
      // function rollDie(numSides) {
      //     if (numSides === undefined) {
      //         numSides = 6
      //     }
      //     return Math.floor(Math.random() * numSides) + 1
      // }
      
      // ============
      // THE NEW WAY!
      // ============
      function rollDie(numSides = 6) {
          return Math.floor(Math.random() * numSides) + 1
      }
      
      function greet(person, msg = "Hey there", punc = '!') {
          console.log(`${msg}, ${person}${punc}`)
    • spread, Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

      • SPREAD for function calls, expands an iterable(array, string, etc.) into a list of arguments
      • const nums = [0, 1, 2, 3];
        Math.max(nums); //NaN
        //Use spread!
        Math.max(...nums); //3
        //same as calling: Math.max(0,1,2,3)
      • SPREAD in array literals, creat a new array using an existing array. Spreads the elements from one array into a new array.可以
      • const nums1 = [1, 2, 3];
        const nums2 = [4, 5, 6];
        
        [...nums1, ...nums2]; // [1, 2, 3, 4, 5, 6]
        //Append all items from arr2 onto arr1
        nums1 = nums1.concat(nums2);

        ['a', 'b', ...nums2]; // ["a", "b", 4, 5, 6] [...nums1, ...nums2, 7, 8, 9]; //[1,2,3,4,5,6,7,8,9]
      • SPREAD in object literals, copies properties from one object into another object literal
      • const feline = { legs: 4, family: 'Felidae' };
        const canine = { isFurry: true, family: 'Caninae' };
        
        const catDog = { ...feline, ...canine };
        
        
        const dataFromForm = {
            email: 'blueman@gmail.com',
            password: 'tobias123!',
            username: 'tfunke'
        }
        const newUser = { ...dataFromForm, id: 2345, isAdmin: false }
        
        console.log(catDog);  // {legs: 4, family: "Caninae", isFurry: true}, feline和canine都有family这个属性,会被第二个重写
        console.log(newUser);  
        // {email: "blueman@gmail.com", password: "tobias123!", username: "tfunke", id: 2345, isAdmin: false}, copy and add.
    • The Arguments Object
      • Available inside every function
      • it is an array-like object
        • has a length property
        • does not have array methods like push/pop
        • contains all the arguments passed to the function
        • not available inside of arrow functions!
      • function sumAll() {
            let total = 0;
            for (let i = 0; i < arguments.length; i++) {
                total += arguments[i];
            }
            return total;
        }
        console.log(sumAll(1, 2, 3, 4, 5)); //15
    • Rest , collects all remaining arguments into an actual array.  The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.
      • // COLLECT THE "REST" IN NUMS:
        function sum(...nums) {
            return nums.reduce((total, el) => total + el)
        }
        sum(7, 8, 9, 10); //34, 求和, 也可以 
        let total = 0;
        for(let n of nums) total + = n;
        return total;
        function raceResults(gold, silver, ...everyoneElse) { console.log(`GOLD MEDAL GOES TO: ${gold}`) console.log(`SILVER MEDAL GOES TO: ${silver}`) console.log(`AND THANKS TO EVERYONE ELSE: ${everyoneElse}`) } raceResults("Lily", "Keven", "Bob", "Soffi", "Gorge"); //GOLD MEDAL GOES TO: Lily //SILVER MEDAL GOES TO: Keven //AND THANKS TO EVERYONE ELSE: Bob,Soffi,Gorge

    • Destructuring,a  short. clean syntax to "unpack": 
      • values from arrays
      • properties from objects

          into distinct variables.

      • // ===================
        // ARRAY DESTRUCTURING
        // ===================
        const scores = [929321, 899341, 888336, 772739, 543671, 243567, 111934];
        
        // const highScore = scores[0];
        // const secondHighScore = scores[1];
        
        const [gold, silver, bronze, ...everyoneElse] = scores;
        // gold = 929321, silver = 899341, bronze = 888336, everyoneElse = [772739, 543671, 243567, 111934]
        
        // ===================
        // OBJECT DESTRUCTURING
        // ===================
        const user = {
            email: 'harvey@gmail.com',
            password: 'sCoTt1948sMiTh',
            firstName: 'Harvey',
            lastName: 'Milk',
            born: 1930,
            died: 1978,
            bio: 'Harvey Bernard Milk was an American politician and the first openly gay elected official in the history of California, where he was elected to the San Francisco Board of Supervisors',
            city: 'San Francisco',
            state: 'California'
        }
        
        const user2 = {
            email: 'Stacy@gmail.com',
            firstName: 'Stacy',
            lastName: 'Gonzalez',
            born: 1987,
            city: 'Tulsa',
            state: 'Oklahoma'
        }
        
        // const firstName = user.firstName;
        // const lastName = user.lastName;
        // const email = user.email;
        const { email, firstName, lastName, city, bio } = user;
        
        //change the  name,use "=" to set default value
        const { born: birthYear, died: deathYear = 'N/A' } = user;
        
        const { city, state, died = 'N/A' } = user2;
        
        // ===================
        // PARAM DESTRUCTURING
        // ===================
        
        function fullName(user) {
            return `${user.firstName} ${user.lastName}`
        }
        function fullName(user) {
            const { firstName, lastName } = user;
            return `${firstName} ${lastName}`
        }
        
        
        function fullName({ firstName, lastName }) {
            return `${firstName} ${lastName}`
        }
        
        
        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
            }
        ]
        
        
        movies.filter((movie) => movie.score >= 90)
        movies.filter(({ score }) => score >= 90)   //use {} to position the score parameter
        
        
        movies.map(movie => {
            return `${movie.title} (${movie.year}) is rated ${movie.score}`
        })
        
        movies.map(({ title, score, year }) => {
            return `${title} (${year}) is rated ${score}`
        })
  • 相关阅读:
    STL特性总述——写在前面
    C++多线程框架
    C++内存管理之unique_ptr
    ubuntu文本模式/终端中文乱码解决
    log4net日志在app.config中assembly不起作用
    解决多线程委托二义性问题
    IIS 中文文件名下载会出现403访问被拒绝
    C# 异常:从作用域“”引用了“FiasHostApp.Entity.DBEntity.FIAS_RM_v1.ITraNetMgrUnitBaseInfoRecord”类型的变量“w”,但该变量未定义
    C# string.Split对于换行符的分隔正确用法
    knockoutJS+knockout.multimodels使用记录
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14270641.html
Copyright © 2011-2022 走看看