美文网首页
2019-12-30 es6基本语法

2019-12-30 es6基本语法

作者: 李华峰0722 | 来源:发表于2019-12-30 10:07 被阅读0次

    1. Let 和 Const

    {
        var a = 10
        let b = 20
        const c = 30
    }
    a // 10
    b // Uncaught ReferenceError: b is not defined
    c // c is not defined
    let d = 40
    const e = 50
    d = 60
    d // 60
    e = 70 // VM231:1 Uncaught TypeError: Assignment to constant variable.
    

    2.类(Class)

    function Person(name, age) {
        this.name = name
        this.age = age
    }
    Person.prototype.information = function () {
        return 'My name is ' + this.name + ', I am ' + this.age
    }
    

    //es6

    class Person {
        constructor(name, age) {
            this.name = name
            this.age = age
        }
        information() {
            return 'My name is ' + this.name + ', I am ' + this.age
        }
    }
    

    3. 箭头函数(Arrow function)

    var list = [1, 2, 3, 4, 5, 6, 7]
    var newList = list.map(function (item) {
        return item * item
    })
    

    //es6

    const list = [1, 2, 3, 4, 5, 6, 7]
    const newList = list.map(item => item * item)
    

    4.函数参数默认值(Function parameter defaults)

    function config (data) {
        var data = data || 'data is empty'
    }
    

    //es6

    const config = (data = 'data is empty') => {}
    

    例1:

    // 给方法添加默认参数值
    function foo( a = 5, b = 10) {
        console.log( a + b);
    } 
    foo();  // 15
    foo( 7, 12 );  // 19
    foo( undefined, 8 ); // 13
    foo( 8 ); // 18
    foo( null ); // 10 as null is coerced to 0
    

    例2:

    // 默认参数值也可以是表达式或者函数
    function foo( a ) { return a * 4; }
     
    // y = x + 4, z = foo(x)
    function bar( x = 2, y = x + 4, z = foo(x)) {
        console.log([ x, y, z ]);
    }
     
    bar();  // [ 2, 6, 8 ]
    bar( 1, 2, 3 ); //[ 1, 2, 3 ] 
    bar( 10, undefined, 3 );  // [ 10, 14, 3 ]
    

    例3:

    // 对象参数默认值,如果参数为空,则会抛出异常
    function show({ title = "title", width = 100, height = 200 }) {
      console.log( `${title} ${width} ${height}` );
    }
    show() // Cannot destructure property `title` of 'undefined' or 'null'.
    show({}) // title 100 200
     
    // 解决办法:
    function show({ title = "title", width = 100, height = 200 } = {}) {
      console.log( `${title} ${width} ${height}` );
    }
     
    show(); // title 100 200
    show({width: 200}) // title 200 200
    

    5.模板字符串(Template string)

    var name = 'kris'
    var age = 24
    var info = 'My name is ' + this.name + ', I am ' + this.age
    //es6
    const name = 'kris'
    const age = 24
    const info = `My name is ${name}, I am ${age}`
    

    函数分两种情况:

    1. 函数本身,同样会调用它的tostring()方法
    2. 直接调用函数,则输出函数的返回值
    var fn1 = function(){
    console.log('hello vuex');
    }
    var fn2 = function(){
    return 'hello vue-router'
    }
    `xxx ${fn1}`//xxx function fn(){....}
    `xxx ${fn1()}`//xxx underfind
    `xxx ${fn2()}`//xxx hello vue-router
    

    6.解构赋值(Destructuring assignment)

    例1:

    let a = 10
    let b = 20
    [a, b] = [b, a]
    

    例2(声明多个变量):

    // 声明变量
    let age = 22
    let name = 'guodada'
    let sex = 1
    

    // better

    let [age, name, sex] = [22, 'aa', 1]
    console.log(age, name, sex) //22 "aa" 1
    

    例3(使用在对象中):

    const obj = {
      name: {
        firstName: 'guo',
        lastName: 'dada'
      }
    }
    
    // 提取变量
    const firstName = obj.name.firstName
    const lastName = obj.name.lastName
    

    // better

    const { firstName, lastName } = obj.name 
    

    例4(使用在函数中):

    // 在参数中结构赋值,获取参数, 当参数多的使用时候十分方便

    function Destructuring({ name, age }) {
      return { name, age } // 相当于 { name: name, age: age } , 可以简写
    }
    
    const params = { name: 'guodada', age: 22 }
    Destructuring(params)
    

    例5:key变量重命名, first --> firstName

    // key变量重命名, first --> firstName
    const person = {
      first: 'foo',
      last: 'tom',
    };
     
    const { first: firstName } = person;
    console.log(firstName); // foo
    

    例6:默认值

    // 默认值
    const settings = {
        speed: 150
    }
    const { speed = 750, width = 500 } = settings;
    console.log(speed); // 150 
    console.log(width); // 500
     
    // 可能不存在的key
    const { middle: middleName = 'midname' } = person;
    console.log(middleName); // 'midname'
    

    例6:嵌套赋值

    // 嵌套赋值
    const user = {
      id: 339,
      name: 'Fred',
      age: 42,
      education: {
        degree: 'Masters'
      }
    };
    const {education: {degree}} = user;
    console.log(degree); //prints: Masters
    

    如果嵌套的属性不存在

    // 如果嵌套的属性不存在
    const user = {
      id: 339,
      name: 'Fred',
      age: 42
    };
    const {education: {degree}} = user;  // TypeError: Cannot match against 'undefined' or 'null'.
     
    // 解决办法:
    const user = {
      id: 339,
      name: 'Fred',
      age: 42
    };
    const {education: {degree} = {}} = user;
    console.log(degree); //prints: undefined
    

    7.扩展操作符(Spread operator)

    function sum(x, y, z) {
        return x + y + z;
    }
    var list = [5, 6, 7]
    var total = sum.apply(null, list)
    

    //es6

    const sum = (x, y, z) => x + y + z
    const list = [5, 6, 7]
    const total = sum(...list)
    

    主要用途:

    let a = [1, 2, 3]
    let b = [...a] // b是一个新的数组,内容和a一样
    let c = [...a, 4, 5, 6]
     
    let car = { type: 'vehicle ', wheels: 4};
    let newCar = {...car}
    console.log(newCar); // { type: 'vehicle ', wheels: 4}
    
    // 合并对象属性,后边的属性会覆盖前边的,可用于修改对象的某个属性值
    let car2 = {...car, type: 'vehicle2', wheels: 2} // {type: "vehicle2", wheels: 2}
    
    function foo(...args) {
       console.log(args); 
    } 
    foo( 'car', 54, 'tree');  //  console.log 输出 [ 'car', 54, 'tree' ]
    

    8.对象属性简写(Object attribute shorthand)

    var cat = 'Miaow'
    var dog = 'Woof'
    var bird = 'Peet peet'
    
    var someObject = {
      cat: cat,
      dog: dog,
      bird: bird
    }
    

    //es6

    let cat = 'Miaow'
    let dog = 'Woof'
    let bird = 'Peet peet'
    
    let someObject = {
      cat,
      dog,
      bird
    }
    
    console.log(someObject)
    
    //{
    //  cat: "Miaow",
    //  dog: "Woof",
    //  bird: "Peet peet"
    //}
    

    9.for...of

    for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。

    const array1 = ['a', 'b', 'c'];
    
    for (const element of array1) {
          console.log(element)
    }
    
    // "a"
    // "b"
    // "c"
    

    10. Set

    const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
    console.log([...new Set(numbers)]) 
    // [2, 3, 4, 5, 6, 7, 32]
    

    11. Map

    Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。
    例子如下,我们甚至可以使用NaN来作为键值:

    var myMap = new Map();
    myMap.set(NaN, "not a number");
    
    myMap.get(NaN); // "not a number"
    
    var otherNaN = Number("foo");
    myMap.get(otherNaN); // "not a number"
    

    12.Array对象的扩展

    (1)Array.prototype.from:转换具有Iterator接口的数据结构为真正数组,返回新数组。

    console.log(Array.from('foo')) // ["f", "o", "o"]
    
    console.log(Array.from([1, 2, 3], x => x + x)) // [2, 4, 6]
    // 等同于
    Array.from([1,2,3].map(x => x * x))
    

    Array.from()可以将各种值转为真正的数组,并且还提供map功能。这实际上意味着,只要有一个原始的数据结构,你就可以先对它的值进行处理,然后转成规范的数组结构,进而就可以使用数量众多的数组方法。

    Array.from({ length: 2 }, () => 'jack')// ['jack', 'jack']
    

    (2)Array.prototype.of():转换一组值为真正数组,返回新数组。

    Array.of(7)       // [7] 
    Array.of(1, 2, 3) // [1, 2, 3]
    
    Array(7)          // [empty, empty, empty, empty, empty, empty]
    Array(1, 2, 3)    // [1, 2, 3]
    

    (3)Array.prototype.find():返回第一个符合条件的成员

    const array1 = [5, 12, 8, 130, 44]
    
    const found = array1.find(element => element > 10)
    console.log(found) // 12
    //如果没找到,就返回undefined
    

    (4)Array.prototype.keys():返回以索引值为遍历器的对象

    const array1 = ['a', 'b', 'c']
    const iterator = array1.keys()
    
    for (const key of iterator) {
        console.log(key)
    }
    
      // 0
      // 1
      // 2
    

    (5)Array.prototype.values():返回以属性值为遍历器的对象

      const array1 = ['a', 'b', 'c']
      const iterator = array1.values()
    
      for (const key of iterator) {
            console.log(key)
      }
    
      // a
      // b
      // c
    

    (6)Array.prototype.entries():返回以索引值和属性值为遍历器的对象

      const array1 = ['a', 'b', 'c']
      const iterator = array1.entries()
    
      console.log(iterator.next().value) // [0, "a"]
      console.log(iterator.next().value) // [1, "b"]
    

    13.Array.prototype.includes()

    includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

    const array1 = [1, 2, 3]
    console.log(array1.includes(2)) // true
    
    const pets = ['cat', 'dog', 'bat']
    console.log(pets.includes('cat')) // true
    console.log(pets.includes('at')) // false
    

    14. Object.keys()、Object.values()、Object.entries() 对象转键值对、Object.fromEntries() 键值对转对象

    const object1 = {
          a: 'somestring',
          b: 42
    }
    console.log(Object.keys(object1)) // ["a", "b"]
    
    const object1 = {
          a: 'somestring',
          b: 42,
          c: false
    }
    console.log(Object.values(object1)) // ["somestring", 42, false]
    
    const object1 = {
          a: 'somestring',
          b: 42
    }
    
    for (let [key, value] of Object.entries(object1)) {
          console.log(`${key}: ${value}`)
    }
    
    // "a: somestring"
    // "b: 42"
    

    Object.fromEntries() 方法把键值对列表转换为一个对象,它是Object.entries()的反函数。

    const entries = new Map([
      ['foo', 'bar'],
      ['baz', 42]
    ])
    
    const obj = Object.fromEntries(entries)
    
    console.log(obj) // Object { foo: "bar", baz: 42 }
    

    15. padStart()

    padStart() 方法用另一个字符串填充当前字符串(重复,如果需要的话),以便产生的字符串达到给定的长度。填充从当前字符串的开始(左侧)应用的。

    代码如下:

    const str1 = '5'
    console.log(str1.padStart(2, '0')) // "05"
    
    const fullNumber = '2034399002125581'
    const last4Digits = fullNumber.slice(-4)
    const maskedNumber = last4Digits.padStart(fullNumber.length, '*') 
    console.log(maskedNumber) // "************5581"
    

    16. padEnd()

    padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

    const str1 = 'Breaded Mushrooms'
    console.log(str1.padEnd(25, '.')) // "Breaded Mushrooms........"
    const str2 = '200'
    console.log(str2.padEnd(5)) // "200  "
    

    17.对象扩展操作符

    ES6中添加了数组的扩展操作符,让我们在操作数组时更加简便,美中不足的是并不支持对象扩展操作符,但是在ES9开始,这一功能也得到了支持,例如:

    var obj1 = { foo: 'bar', x: 42 };
    var obj2 = { foo: 'baz', y: 13 };
    
    var clonedObj = { ...obj1 };
    // 克隆后的对象: { foo: "bar", x: 42 }
    
    var mergedObj = { ...obj1, ...obj2 };
    // 合并后的对象: { foo: "baz", x: 42, y: 13 }
    

    上面便是一个简便的浅拷贝。这里有一点小提示,就是Object.assign() 函数会触发 setters,而展开语法则不会。所以不能替换也不能模拟Object.assign() 。

    如果存在相同的属性名,只有最后一个会生效。

    相关文章

      网友评论

          本文标题:2019-12-30 es6基本语法

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