ES6小结

 let
1. 不允许重复声明。
2. 块级作用域
3. 不允许变量提升,必须先声明再使用。
4. 不影响作用域链。

const
1. 一定要赋初始值。
2. 原则上用大写。(非强制性)
3. 值不能修改。
4. 块级作用域。
5. 对数组/对象元素修改不会报错。
const TEAM = ['A','B','C'];
TEAM.push('D'); //影响值,不会报错

TEAM = ['F'];  //影响地址,报错
解构赋值
1. 数组
const F = ['AA','BB','CC','DD']
let [A,B,C,D] = F
console.log(A); // AA

2. 对象
const ZHAO =
    {name:'zhao',age:'1',
     xiaopin:function(){
        console.log('111111');
    }};
let {name,age,xiaopin} = zhao;
console.log(name);  // zhao

模板字符串
1. `` 用反引号声明。
2. 内容可以出现换行符等格式符号,即保留字符串内部格式。
3. 可以使用 ${} 进行变量拼接。

箭头函数
1. this 是静态的,始终指向函数声明所在的对象,而不是使用时所在的对象。
2. 不能作为构造函数实例化对象,即不能使用new命令。
3. 不能用arguments变量。

window.name = '123';
const school = {name:'345'}

function getName(){
    console.log(this.name);
}
let getName2 = () => {
    console.log(this.name);
}
// 直接调用两个方法都会直接输出 123

// 但用call会改变作用域,但使用箭头函数不会受影响
getName.call(school);  // 345
getName2.call(school); //123

参数默认值
  •  函数传参时如果没有传入指定值,则使用原本设定的默认值。
function add(a,b,c=10){
    // 赋默认值的参数通常放在最后,
}
// 可以配合解构赋值使用
function connect({host,username}){
    console.log(host);  // localhost
}
connect({host:'localhost',username:'root'})

rest参数
  • ES5返回对象arguments,ES6返回数组

// 多参数时,...args默认放后面
function date(...args){
    console.log(args);
}

扩展运算符
  •  把argument的一个数组参数拆分。
  •  数组合并

const a = [...arr1,...arr2]
  •  数组克隆(浅拷贝)

const arr1 = [...arr2] // 克隆arr2
  •  把伪数组变为真数组

const arr = [...arr1]

 Symbol
  • 七种基础数据类型
  • U   S (string / symbol)   O   N(null / number)   B
  • 唯一性
  • 不能参与运算
  • 常用于给已有的对象添加方法,确保安全,不破坏原有属性

let game = {};  //原有对象,可能已经有up down的,但不确定
let methods = {
    up: Symbol(),
    down: Symbol()
}
// 添加两个新的方法,不影响原来的属性,哪怕重名
game[methods.up] = function(){};  
game[methods.down] = function(){};

// 另一种格式
let a = {
    [Symbol('say')]:function(){}
}

迭代器(Iterator)
  •  可用for...of遍历键值(面向对象)
  •  Array/Arguments/Set/Map/String/TypedArray/NodeList
  •  例:按要求每次返回stus的一个变量

const banji = {
    name:'yiban',
    stus:['xiaoming','xiaohong','xiaolv'],
    [Symbol.iterator](){
        let index = 0;   // 索引
        let _this = this;
        return{
            next:function(){
                if(index < _this.stus.length){
                    const result = {value:_this.stus[index],done:false};
                    index++;
                    return result;
                }else{
                    return {value:undefined,done:true}
                }
            }
        }
    }
}

生成器
  • 实现异步编
  • 配合yield逐步执行

// 声明和调用方式

function* gen(){}
let iterator = gen();
iterator.next()

Promise
  • 实现异步编程
  • 链式调用可以解决回调地狱
 Set
  • 数组去重

let result = [...new Set(arr)] // 用Set去重,再用...变回数组

  • 数组求交集

let result = [...new Set(arr)].filter(item => {
    let s2 = new Set(arr2);
    if(s2.has(item)){
        return true;
    }else{
        return false;
    }
})
// 以上代码可以简化为:
let result = [...new Set(arr)].filter(item => new Set(arr2).has(item))








posted @ 2022-07-18 11:47  Arica-ss  阅读(34)  评论(0)    收藏  举报