es6

134 阅读2分钟

6.1 方括号语法

  • 方括号语法的用法 const prop = 'age';
  • 方括号语法可以写在对象字面量中
       const person = {
         [prop]:18
       }
       console.log(person);
    方括号中可以放什么?
    ${};
    [值或通过计算可以得到的(表达式)]
    const prop = 'age';
    const func = () => 'age';
    const person = {
        // [prop]:20
        // [func()]:18
        ['sex']:'male'
    }
    console.log(person);
  • 方括号语法和点语法的区别:点语法是方括号语法的特殊形式 const person = {}
  • person.age等价于person['age']
  • 属性名由数字、字母、下划线以及$构成,并且数字还不能打头的时候可以使用点语法(合法)age18_$
  • 合法标识符可以用来作为变量或常量名
  • 当你的属性或方法名是合法标识符时,可以使用点语法,其他情况下请使用方括号语法

6.2 属性和方法的简洁表示法

  • 实例化构造函数生成对象
    const person = new Object();
    person.age = 18;
    person.speak = function(){}
    console.log(person);
  • 对象字面量
     const person = {
        age:18,
        speak:function(){}
    }
  • 属性的简洁表示法:键名和变量或常量名一样的时候,可以只写一个
    const age = 18;
    const person = {
        // age:age
        age
    }
    console.log(person);
  • 方法的简洁表示法:方法可以省略冒号和function关键字
    const person = {
        speak(){}
    }
    console.log(person);

7.1 函数参数的默认值

  • 调用函数的时候传参了,就用传递的参数,如果没传参,就用默认值
  • 函数参数默认值的基本用法
    const multiply = (x,y=3) => x * y;
    console.log(multiply(9));

7.2 函数参数的默认值的注意事项

  • 不传参数,或者明确的传递undefined作为参数,只有这两种情况下,默认值才会生效
    const multiply = (x,y=3) => x*y;
    console.log(multiply(2));
  • 函数参数的默认值,最好从参数列表的右边开始设置 const multiply = (x,y=3) => x*y;

8.1 剩余参数

  • 剩余参数的本质
  • 剩余参数永远是个数组,即使没有值,也是空数组
    const add = (x,y,z,...args) => {
        console.log(x,y,z,args);
    }
    add(1,2,3,4,5)

8.2 剩余参数的注意事项

  • 箭头函数的参数部分即使只有一个剩余参数,也不能省略圆括号 const add = (...args)=>{}
  • 使用剩余参数替代arguments获取实际参数
    const add = (...args) => {
        console.log(args);
    }
    add(1,2);
  • 剩余参数只能是最后一个参数,之后不能再有其他参数,否则就会报错

8.3 剩余参数的应用

  • 完成add函数
        const add = (...args)=>{
        let sum = 0;
        for(let i=0;i<args.length;i++){
            sum += args[i]
        }
        return sum;
    }
    console.log(add(1,2,3));
    // 与解构赋值结合使用
    // 剩余参数不一定非要作为函数参数使用
    const[num,...args] = [1,2,3,9];
    // 必须是最后一个参数
    console.log(num,args);

    const func = ([num,...args]) => {};
    func([1,2,3])

    const {x,y,...z} = {a:3,x:1,y:2,b:4};
    console.log(x,y,z);

9.1 数组展开运算符

    // 数组展开运算符的基本用法
    console.log(Math.min(...[3,1,2]));
    // 相当于
    console.log(Math.min(3,1,2));

9.2 区分剩余参数和展开运算符

  • 展开运算符[3,1,2] ---> 3,1,2
  • 剩余参数3,1,2 ---> [3,1,2]

9.3 数组展开运算符的应用

  • 复制数组
    const a = [1,2];
    const c = [...a];
    a[0]=3;
    console.log(a);
  • 合并数组
    const a = [1,2];
    const b = [3];
    const c = [4,5];
    console.log([...a,...b,...c]);
  • 字符串转为数组
    // 字符串可以按照数组的形式展开
    console.log(...'alex');
  • 常见的类数组转化为数组(arguments)
    function func(){
        console.log([...arguments]);
    }
    func(1,2)
  • NodeList
console.log([...document.querySelectorAll('p')].push);