其他我爱编程

ES6 快速入门与使用

2018-04-14  本文已影响182人  magic_pill

一、简介

发布时间 版本 别名
2016年6月 ES6.1 ES7、ES2016
2017年6月 ES6.2(async await) ES8、ES2017

二、 let 和 const

1.let
function func(arg){
    let arg;    //报错
}
function func2(arg){
    {
        let arg:    //不报错
    }
}
var arr = [];
for (var i=0;i<3;i++){
    var fun = function () {
        console.log(i);
    };
    arr.push(fun);
}

arr[1]();   //3
var arr = [];
for (let i=0;i<3;i++){
    var fun = function () {
        console.log(i);
    };
    arr.push(fun);
}

arr[1]();   //1
2.const
    (function(){
        //TODO
    })()

三、解构赋值:

//解构json:
let json = {
    name:'YJW',
    age:18,
    job:'coding'
};
let {name,age,job} = json;  //其中 {} 中的名字要和 JSON 中的 key 必须对应,否则会找不到,结果为 undefined
console.log (name,age,job);  //YJW 18 coding
let {name:n,age:g, job:a} = json;
let json = {
    name:'YJW',
    age:18,
    job:'coding'
};
let {name:n,age:a, job:j} = json;  //给变量起别名,此时只能用别名,不能再使用 name、age、job,只能用别名
console.log (n,a,j);  //YJW 18 coding
let [e,f,g] = [12,23];
console.log(e,f,g);  //12 23 undefined
let [e,f,g=34] = [12,23];
console.log(e,f,g);  //12 23 34
null 和 undefined 的区别:
let [e,f,g=34] = [12,23,undefined];
console.log(e,f,g);  //12 23 34
let [e,f,g=34] = [12,23,null];
console.log(e,f,g);  //12 23 null
 //说明如果值为 null 时,默认值不能生效
交换两个数的位置:
let h = 12;
let i = 5;
[h,i] = [i,h];
console.log(h,i);   //5 12
let j;
({j} = {j:111});  //此处的 {j} 限定了作用域,如果不加小括号会报错
console.log(j);

四、字符串模板:

let name ='Strive';
let age = 18;
let str = `这个人叫${name}, 年龄是 ${age}岁`;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>string</title>
</head>
<body>
    <ul id="news"></ul>
    <script>
        let newsArr = [
            {title:"2018博鳌亚洲论坛年会",read:12},
            {title:"中朝启动志愿军烈士陵园修缮工程 ",read:33},
            {title:"捍卫国家利益,我们有底气!",read:44},
            {title:"中国是亚洲经济增长的重要后盾",read:55},
            {title:"美国的任性行为破坏国际贸易秩序 损人不利己",read:66}
        ];

        window.onload = function () {
            //var newUl = document.getElementById("news");
            var newUl = document.querySelector("#news");

            for(var i=0; i<newsArr.length; i++){
                var li = document.createElement("li");
                li.innerHTML = `新闻标题:${newsArr[i].title},
                                阅读人数:${newsArr[i].read}`;
                newUl.appendChild(li);
            }
        };
    </script>
</body>
</html>
ES2016 新增的内容
navigator.userAgent.includes("Chrome");
"yjw".repeat(3);  //yjwyjwyjw
let str = "aaa";
let padStr = "bbb";
console.log(str.padStart(str.length+padStr.length,padStr));  //bbbaaa

五、函数变化:

1. 函数默认参数
- 之前:
function show(a,b) {
    a = a || "Wel ";
    console.log(a + b);
}
show("Welcome ","YJW");  //Welcome YJW
show("Welcome ","");  //Welcome
show("","YJW");  //Wel YJW
function show({x=0,y=0}={}){
    console.log(x,y);
}
show();
函数参数默认已经定义了,函数的参数作用范围在函数体内,不能再使用let,const声明
function show(a=18){
    let a = 101;  //错误
    console.log(a);
}
show()
2. rest运算符(扩展运算符):...
var arr = [1,2,3,4,5];
console.log(...arr);  //1 2 3 4 5
function arrSort(...a) {
    console.log(a.sort());    //[1, 2, 3, 8, 9]
}
arrSort(2,1,3,9,8);
3. 箭头函数:=>
function show1() {
    return 1;
}
console.log(show1());  //1
let show2 = ()=>1;
console.log(show2());  //1
(参数) =>{
    语句
    return
}
function Person() {
    this.name = "yjw";
}
let pers = new Person();
console.log(pers.name);
let Person2 = ()=>{
    this.name = "yjw";
};
let person = new Person2();
console.log(person.name);   //报错 Person2 is not a constructor

六、数组

1. ES5里面新增一些东西
var arr = ["apple","banana","pear"];
arr.forEach(function (value,index) {
    console.log(value,index);
});
结果:
  apple 0
  banana 1
  pear 2
let newsArr = [
    {title:"2018博鳌亚洲论坛年会",read:12},
    {title:"中朝启动志愿军烈士陵园修缮工程 ",read:33},
    {title:"捍卫国家利益,我们有底气!",read:44},
    {title:"中国是亚洲经济增长的重要后盾",read:55},
    {title:"美国的任性行为破坏国际贸易秩序 损人不利己",read:66}
];
let newArr = newsArr.map(function (value,index) {
    let json = {};
    json.t = `hei${value.title}`;
    json.r = value.read+100;
    return json;
});
console.log(newArr);
结果:
  [{t: "hei2018博鳌亚洲论坛年会", r: 112},
   {t: "hei中朝启动志愿军烈士陵园修缮工程 ", r: 133},
   {t: "hei捍卫国家利益,我们有底气!", r: 144},
   {t: "hei中国是亚洲经济增长的重要后盾", r: 155},
   {t: "hei美国的任性行为破坏国际贸易秩序 损人不利己", r: 166}]
let newsArr = [
    {title:"2018博鳌亚洲论坛年会",read:12,top:true},
    {title:"中朝启动志愿军烈士陵园修缮工程 ",read:33,top:true},
    {title:"捍卫国家利益,我们有底气!",read:44,top:false},
    {title:"中国是亚洲经济增长的重要后盾",read:55,top:true},
    {title:"美国的任性行为破坏国际贸易秩序 损人不利己",read:66,top:false}
];
let newArr = newsArr.filter(function (value,index) {
    return value.top;
});
console.log(newArr);
结果:
  [{title: "2018博鳌亚洲论坛年会", read: 12, top: true},    
   {title: "中朝启动志愿军烈士陵园修缮工程 ", read: 33, top: true},
   {title: "中国是亚洲经济增长的重要后盾", read: 55, top: true}]
let newsArr = [
    {title:"2018博鳌亚洲论坛年会",read:12,top:true},
    {title:"中朝启动志愿军烈士陵园修缮工程 ",read:33,top:true},
    {title:"捍卫国家利益,我们有底气!",read:44,top:false},
    {title:"中国是亚洲经济增长的重要后盾",read:55,top:true},
    {title:"美国的任性行为破坏国际贸易秩序 损人不利己",read:66,top:false}
];
let newArr = newsArr.some(function (value,index) {
    return value.top;
});
console.log(newArr);
结果:true。
let newsArr = [
    {title:"2018博鳌亚洲论坛年会",read:12,top:true},
    {title:"中朝启动志愿军烈士陵园修缮工程 ",read:33,top:true},
    {title:"捍卫国家利益,我们有底气!",read:44,top:false},
    {title:"中国是亚洲经济增长的重要后盾",read:55,top:true},
    {title:"美国的任性行为破坏国际贸易秩序 损人不利己",read:66,top:false}
];
let newArr = newsArr.every(function (value,index) {
    return value.top;
});
console.log(newArr);
结果:false。

let arrNum = [2,3,4,5];
let result = arrNum.reduce(function (accumulator, cur, curIndex, arr) {
    //accumulator 为上一次 return 的值,第一次循环时返回的为数值中第一个值
    //cur 为当前数组的值
    //curIndex 为当前的索引
    //arr 为调用这个方法的数组
    console.log("pre:  "+accumulator);
    console.log("cur:  "+cur);
    console.log("val:  "+curIndex);
    console.log("index:"+arr);
    return (accumulator+cur)
});
console.log(result);
pre:  2
cur:  3
val:  1
index:2,3,4,5
pre:  5
cur:  4
val:  2
index:2,3,4,5
pre:  9
cur:  5
val:  3
index:2,3,4,5
14
let arrNum = [1,3,5,7];
let result = arrNum.reduceRight(function (accumulator, cur, curIndex, arr) {
    //accumulator 为上一次 return 的值,第一次循环时返回的为数值中最后一个值
    //cur 为当前数组的值
    //curIndex 为当前的索引
    //arr 为调用这个方法的数组
    console.log("pre:  "+accumulator);
    console.log("cur:  "+cur);
    console.log("val:  "+curIndex);
    console.log("arr:  "+arr);
    return (accumulator+cur)
});
console.log(result);
pre:  7
cur:  5
val:  2
arr:  1,3,5,7
pre:  12
cur:  3
val:  1
arr:  1,3,5,7
pre:  15
cur:  1
val:  0
arr:  1,3,5,7
16
2. ES6:
let arrNum = ["apple","banana","pear"];
for (let value of arrNum){
    console.log(value);
}
//apple
//banana
//pear
let arrNum = ["apple","banana","pear"];
for (let key of arrNum.keys()){
    console.log(key);
}
//0
//1
//2
let arrNum = ["apple","banana","pear"];
for (let entry of arrNum.entries()){
    console.log(entry);
}
//[0, "apple"]
//[1, "banana"]
//[2, "pear"]
let arrNum = ["apple","banana","pear"];
for (let [key,val] of arrNum.entries()){
    console.log(key,val);
}
//0 "apple"
//1 "banana"
//2 "pear"
let arr =[1,2,3];
let arr2 = [...arr];
let arr3 = Array.from(arr);
//arr2 和 arr3 结果一样。
Array.from:
  作用: 把类数组(一组元素、arguments...) 对象`转成数组`
  暂时发现:具备 length这个东西,就靠谱。比如 JSON 没有 length,但是在 JSON 中添加 `length:2` 就可以解决问题。
let arr = Array.of("aaa","bbb","ccc");
console.log(arr);    //["aaa", "bbb", "ccc"]
let arr = [12,120,13,101];
let num = arr.find(function (val,index) {
    return val>100;
});
console.log(num);    120
let arr = [12,120,13,101];
let num = arr.findIndex(function (val,index) {
    return val>100;
});
console.log(num);
let arr = new Array(5);
arr.fill("aa",1,3);
console.log(arr);  //[empty × 1, "aa", "aa", empty × 2]
let str = "abcdefg";
console.log(str.includes("cd"));  //true
let arr = ["a","b","c","d"];
console.log(arr.indexOf("c"));  //2
console.log(arr.includes("c")); //true 

七、对象:

//之前用法
let a = 1;
let b = 2;
let json ={
    a:a,
    b:b,
    showA:function(){
        return this.a;
    }
    showB:function(){
        return this.b;
    }
}
//现在用法
let json ={
    a,
    b,
    showA(){  //个人建议: 一定注意,不要用箭头函数
    },
    showB(){
    }
}

new Vuex.Store({
    state,
    mutation,
    types,
    actions
});

new Vue({
    router,
    App,
    vuex
});
console.log(NaN == NaN);  //false
console.log(Number.isNaN(NaN));  //true
console.log(Object.is(NaN,NaN));  //true

console.log(+0 == -0);  //true
console.log(Object.is(+0,-0));  //false
console.log(Object.is("aaa","aaa"));  //true
let a = {a:1};
let b = {b:2,a:2};  // 有重复变量时,后面的会覆盖前面的
let c = {c:3};
let json = Object.assign({},a,b,c);
console.log(json);    // {a: 2, b: 2, c: 3}
function ajax(options){  // options 为用户传的参数
    let defaults={
        type:'get',
        header:
        data:{}
        ....
    };

    let json = Object.assign({}, defaults, options);
    .....
}
let arr = ["a","b","c"];
let newArr = Object.assign([],arr);
newArr.push("dd");
console.log(arr);
console.log(newArr);
ES2017引入:
let json = {
    a:111,
    b:222,
    c:333
};
console.log(Object.keys(json));  // ["a", "b", "c"]
console.log(Object.values(json));  // [111, 222, 333]
console.log(Object.entries(json));  // [["a", 111],["b", 222],["c", 333]]
let {keys, values, entries} = Object;
for (let key of keys(obj){
    ....
}
let json = {
    a:111,
    b:222,
    c:333,
    d:444
};

let {a,b,...c} = json;
console.log(a,b,c);  //111 222 {c: 333, d: 444}
let json = {
    a:111,
    b:222,
    c:333,
    d:444
};
let newJson = {...json};
delete newJson.a;
console.log(newJson);  //{b: 222, c: 333, d: 444}
console.log(json);console.log(newJson);  //{a: 111, b: 222, c: 333, d: 444}

八、Promise

ajax(url,{  //获取token
    ajax(url,()=>{  //获取用户信息
        ajax(url, ()=>{
            //获取用户相关新闻
        })
    })
})
let promise = new Promise(function(resolve, reject){
    //resolve,   成功调用
    //reject     失败调用
});

promise.then(res=>{
    ....
}, err=>{
    ....
});

promise.catch(err=>{
    ....
})
let a = 1;
let promise = new Promise(function (resolve, reject) {
    if (a == 10){
        resolve("成功啦。。。");
    }else {
        reject("失败了。。。");
    }
});

promise.then(res=>{
    console.log(res);
},err=>{
    console.log(err);
});
promise.catch(err=>{
    console.log(err);
});
// 失败了。。。
// 失败了。。。
// 如果 let = 10;会打印 “成功啦。。。”
new Promise().then(res=>{
    ....
}).catch(err=>{
    ....
})
let a = 10;
let promise = new Promise(function (resolve, reject) {
    if (a == 10){
        resolve("成功啦。。。");
    }else {
        reject("失败了。。。");
    }
}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
});
// 成功啦。。。
new Promise(resolve =>{
    resolve('aaa')
});
new Promise((resolve, reject) =>{
    reject('aaa')
});
let p1 = Promise.resolve("succ--哈哈哈");
let p2 = Promise.reject("fail--嘿嘿嘿");
p1.then(res=>{
    console.log(res);    // succ--哈哈哈
});
p2.then(res=>{
    console.log(res);
},err=>{
    console.log(err);   // fail--嘿嘿嘿
});
let p1 = Promise.resolve("aaa");
let p2 = Promise.resolve("bbb");
let p3 = Promise.resolve("ccc");

Promise.all([p1,p2,p3]).then(res=>{
    console.log(res);
}).catch(err => {
    console.log(err);
})
// ["aaa", "bbb", "ccc"]
必须确保,所有的promise对象,都是resolve状态,都是成功状态,否则只会返回失败的那个信息
let p1 = Promise.resolve("aaa");
let p2 = Promise.resolve("bbb");
let p3 = Promise.reject("ccc");

Promise.all([p1,p2,p3]).then(res=>{
    console.log(res);
}).catch(err => {
    console.log(err);
});
// ccc
let p1 = Promise.reject("aaa");
let p2 = Promise.resolve("bbb");
let p3 = Promise.resolve("ccc");

Promise.race([p1,p2,p3]).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
});
new Promise(function (resolve, reject) {
    console.log("1111");

    resolve("22222");

    new Promise(function (resolve, reject) {
        resolve("333333")
    }).then(function (res) {
        console.log(res);
    });

    setTimeout(function () {
        console.log("44444");
    },0);

    console.log("66666");
    
}).then(res => {
    console.log(res)
});

console.log("55555");
结果:
    1111
    66666
    55555
    333333
    22222
    44444
    // 发现定时器是最后执行的

九、模块化

模块化:
① export  东西
② export const a =12;
③ export{
      a as aaa,    // 以后导入的时候只能导入 aaa  :import {aaa} from "./a.js";
      b as banana    // 以后导入的时候只能导入 banana
   }
④ export default aaa;  // 导入的方式不需要 {}:import aaa from "./a.js";
<script type="module">
    ① import
    ② import './modules/1.js';
    ③ import {aaa as a, banana as b, cup as c} from './modules/2.js';  // 使用时候只能用 a、b、c
    ④ import * as modTwo from './modules/2.js';
</script>
Promise.all([import("./1.js"),import("./2.js")]).then(([mod1,mod2]) => {
    console.log(mod1);
    console.log(mod2);
});

十、类和继承

人:  Person
    属性: name
    展示名字: showName

    Person.prototype.showName
    function Person(name,age){
        this.name='aaa';
        this.age = age;
    }
    Person.prototype.showName=function(){
        return `名字是:${this.name}`;
    }
    let p1 = new Person("yjw",18);
程序中类
面向对象 ,类
    属性
    方法

ES6中变形:

    class Person{
        constructor(name,age){  //构造方法(函数),调用 new 时,自动执行
            this.name = name;
            this.age = age
        } 
        showName(){
            return `名字是:${this.name}`;
        }
    }
    let p = new Person("yjw",18);
let name = "yjw";
class Person{
    [name](){
        console.log("haha "+name);
    }
}
let p = new Person();
p[name]();  //haha yjw
// [] 中放变量名,这样通过 [] 就可以变成一个属性,属性名可以是表达式
class Person{
    set name(val){
        console.log(`设置了 name 的值,值为:${val}`);
    }

    get name(){
        return `获得了 name 属性的值`;
    }
}

let p = new Person();
p.name = "yjw";    //设置了 name 的值,值为:yjw
console.log(p.name);    //获得了 name 属性的值
class Person{
    showName(){
        return "展示 name";
    }
    static showLog(){
        return "展示 静态方法";
    }
}

let p = new Person();
console.log(p.showName());    //展示 name
console.log(Person.showLog());    //展示 静态方法
继承:
// 之前:
function Person(name) {
    this.name = name;
}
Person.prototype.showName = function () {
    return `名字是:${this.name}`;
};

function Student(name, skill) {
    Person.call(this,name);  // 继承 name 属性
    this.skill = skill;
}

Student.prototype = new Person();   // 继承方法

let p = new Person("yjw");
console.log(p.showName());  //名字是:yjw

let s = new Student("wang");
console.log(s.name);  //wang
console.log(s.showName());  //名字是:wang
//现在: extends
class Person{
    constructor(name){
        this.name = name;
    }
    showName(){
        return `名字是:${this.name}`;
    }
}

class Student extends Person{
    constructor(name,skill){
        super(name);
        this.skill = skill;
    }
}

let s = new Student("yjw","study");
console.log(s.name);    //yjw
console.log(s.showName());  //名字是:yjw
console.log(s.skill);   //study

十一、Symbol

let sym = Symbol("aaa");
console.log(sym);    //Symbol(aaa)
console.log(typeof sym);    //symbol,用 typeof 检测出来数据类型:symbol
let sym = Symbol("aaa");
let json = {
    a:"aaa",
    b:"bbb",
    [sym]:"symbol"
};
for (let key in json){
    console.log(key);
}
//结果
a
b

十二、generator 函数

// 方法一:
function * show(){
    yield
}
//方法二
function* show(){
    yield
}
//方法三
function *show(){
    yield
}
//使用
function * gen() {
    yield 111111;
    yield (function () {return 2222;})();
    return 33333;
}

let g = gen();
console.log(g.next());  //{value: 111111, done: false}
console.log(g.next());  //{value: 2222, done: false}
console.log(g.next());  //{value: 33333, done: true}
console.log(g.next());  //{value: undefined, done: true}

console.log(gen().next());  //{value: 111111, done: false}
console.log(gen().next());  //{value: 111111, done: false}
function * gen() {
    yield 111111;
    yield (function () {return 2222;})();
    yield 333333;
    return 444444;
    yield 555555;
}

for (let val of gen()){
    console.log(val);
}
111111
2222
333333
// return 的东西,不会被遍历
//并且 return 后面的数据也不会被遍历,yield 中的 return 不会被影响
function * gen() {
    yield 111111;
    yield (function () {return 2222;})();
    yield 333333;
    return 444444;
    yield 555555;
}

let [a,b,c,d] = gen();
console.log(a, b, c, d);  //111111 2222 333333 undefined
  1. 扩展运算符:...
function * gen() {
    yield 111111;
    yield (function () {return 2222;})();
    yield 333333;
    return 444444;
    yield 555555;
}

let [a,...b] = gen();
console.log(a, b);
// 111111 [2222, 333333]
function * gen() {
    yield 111111;
    yield (function () {return 2222;})();
    yield 333333;
    return 444444;
    yield 555555;
}

let arr =Array.from(gen());
console.log(arr);  //[111111, 2222, 333333]

十三、async

async function fn(){  //表示异步,这个函数里面有异步任务
    let result = await  xxx //表示后面结果需要等待    
}
nodeJs 中读取文件 fs.readFile。
//1. promise
let fs = require("fs");

let read = function (fileName) {
    return new Promise((resolve,reject) => {
        fs.readFile(fileName,function (err,res) {
            if (err) reject(err);
            resolve(res)
        });
    });
};

read("./aaa.txt").then(res=>{
    console.log(res.toString());
    return read("./bbb.txt");
}).then(res=>{
    console.log(res.toString());
    return read("./ccc.txt");
}).then(res=>{
    console.log(res.toString());
});
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//bbbbbbbbbbbbb
//cccccccccccc
//2. genrator
let fs = require("fs");

let read = function (fileName) {
    return new Promise((resolve,reject) => {
        fs.readFile(fileName,function (err,res) {
            if (err) reject(err);
            resolve(res)
        });
    });
};

function * gen(){
    yield read("./aaa.txt");
    yield read("./bbb.txt");
    yield read("./ccc.txt");
}
let g = gen();
g.next().value.then(res => {
    console.log(res.toString());
    return g.next().value;
}).then(res => {
    console.log(res.toString());
    return g.next().value;
}).then(res => {
    console.log(res.toString());
});
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//bbbbbbbbbbbbb
//cccccccccccc
//3. async
let fs = require("fs");

let read = function (fileName) {
    return new Promise((resolve,reject) => {
        fs.readFile(fileName,function (err,res) {
            if (err) reject(err);
            resolve(res)
        });
    });
};
async function fn() {
    let f1 = await read("./aaa.txt");
    console.log(f1.toString());

    let f2 = await read("./bbb.txt");
    console.log(f2.toString());

    let f3 = await read("./ccc.txt");
    console.log(f3.toString());
}

fn();
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//bbbbbbbbbbbbb
//cccccccccccc

如何解决async函数中抛出错误,影响后续代码:
a).
try{

    }catch(e){
        
    }
b). promise本身catch

个人建议大家:
try{
let f1 = await readFile('data/a.txt');
let f3 = await readFile('data/c.txt');
let f2 = await readFile('data/b.txt');
}catch(e){}


async await

数据结构
数组
json, 二叉树....

set数据结构:
类似数组,但是里面不能有重复值

let arr = ['a','b','a'];

let arr = new Array();

set用法:
let setArr = new Set(['a','b']);

setArr.add('a');   往setArr里面添加一项
setArr.delete('b'); 删除一项
setArr.has('a') 判断setArr里面有没有此值
setArr.size 个数

setArr.clear(); 清空

for...of...

循环:
    a). for(let item of setArr){  //默认是values()
                console.log(item);
            }
    b). for(let item of setArr.keys()){console.log(item);}
    c). for(let item of setArr.values()){}
    d). for(let [k,v] of setArr.entries()){}
    
    e). setArr.forEach((value,index) =>{
                console.log(value, index);
            });

let setArr = new Set().add('a').add('b').add('c');

数组去重:
let arr = [1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4,4];
let newArr = [...new Set(arr)];
console.log(newArr);

set数据结构变成数组:
[...set]

想让set使用数组的,map循环和filter:


let arr = [{},{}];

new Set([]); 存储数组, 这种写法对

new WeakSet({}) 存储json,这种写法不靠谱

WeakSet没有size,也没有clear()

有, add(), has(), delete()

确认,初始往里面添加东西,是不行的。最好用add添加

总结: new Set()

let json ={
p1:1,
b:2
};


map:
类似 json, 但是json的键(key)只能是字符串

map的key可以是任意类型

使用:
let map = new Map();

map.set(key,value);    设置一个值

map.get(key)    获取一个值

map.delete(key) 删除一项

map.has(key)    判断有没有

map.clear() 清空

循环:
for(let [key,value] of map){}

for(let key of map.keys()){}

for(let value of map.values()){}

for(let [k,v] of map.entries()){}

map.forEach((value, key) =>{
    console.log(value, key);
})

WeakMap(): key只能是对象


总结:
Set 里面是数组,不重复,没有key,没有get方法
Map 对json功能增强,key可以是任意类型值


数字(数值)变化:
二进制: (Binary)
let a = 0b010101;
八进制: (Octal)
let a = 0o666;

十六进制:
    #ccc
-------------------------------------------
Nunber()、parseInt()、 parseFloat()
-------------------------------------------

Number.isNaN(NaN)   -> true

Number.isFinite(a)   判断是不是数字    √

Number.isInteger(a)  判断数字是不是整数  √

-------------------------------------------
Number.parseInt();
Number.parseFloat();

安全整数:
2**3

安全整数:    -(2^53-1) 到 (2^53-1),   包含-(2^53-1) 和(2^53-1)

Number.isSafeInteger(a);

Number.MAX_SAFE_INTEGER 最大安全整数
Number.MIN_SAFE_INTEGER 最小安全整数

Math:
Math.abs()
Math.sqrt()
Math.sin()

Math.trunc()    截取,只保留整数部分
    Math.trunc(4.5)  ->  4
    Math.trunc(4.9)  ->  4

Math.sign(-5)   判断一个数到底是正数、负数、0
    Math.sign(-5)  ->  -1
    Math.sign(5)  -> 1
    Math.sign(0)    ->  0
    Math.sign(-0)   ->  -0
    其他值,返回 NaN

Math.cbrt() 计算一个数立方根

    Math.cbrt(27)  ->  3

.......

ES2018(ES9):
1. 命名捕获
语法: (?<名字>)

    let str = '2018-03-20';
    let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
    let {year, month ,day} = str.match(reg).groups;
    console.log(year, month, day);
反向引用:
    \1  \2     $1  $2
反向引用命名捕获:
    语法:  \k<名字>

    let reg = /^(?<Strive>welcome)-\k<Strive>$/;

    匹配: ‘welcome-welcome’

    -------------------------------------------------

    let reg = /^(?<Strive>welcome)-\k<Strive>-\1$/;

    匹配: 'welcome-welcome-welcome'

替换:
    $<名字>

    let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
    str = str.replace(reg,'$<day>/$<month>/$<year>');
    console.log(str);

    ----------------------------------------
    str = str.replace(reg, (...args)=>{
        //console.log(args)
        let {year, month, day} = args[args.length-1];

        return `${day}/${month}/${year}`;
    });

    console.log(str);

2.   dotAll 模式  s

    之前 '.' 在正则里表示匹配任意东西, 但是不包括 \n 

   let reg = /\w+/gims;

3. 标签函数
    function fn(){

    }

    fn()  //这样调用就是普通函数

    fn`aaa`  //标签函数使用

    -----------------------------------
    function fn(args){
        return args[0].toUpperCase();
    }

    console.log(fn`welcome`);

ES2018(ES9)

proxy: 代理
扩展(增强)对象、方法(函数)一些功能

比如: 
    Vue

    Vue.config.keyCodes.enter=65

Proxy作用: 比如vue中拦截
    预警、上报、扩展功能、统计、增强对象等等

proxy是设计模式一种,  代理模式

let obj ={
name:'Strive'
};
//您访问了name
obj.name // Strive


语法:
new Proxy(target, handler);
let obj = new Proxy(被代理的对象,对代理的对象做什么操作)

handler:

{
    set(){},  //设置的时候干的事情
    get(){},  //获取干的事情
    deleteProperty(){},  //删除
    has(){}  //问你有没有这个东西  ‘xxx’ in obj
    apply()  //调用函数处理
    .....
}

实现一个,访问一个对象身上属性,默认不存在的时候给了undefined,希望如果不存在错误(警告)信息:


DOM.div()
DOM.a();
DOM.ul()


set(), 设置,拦截:
设置一个年龄,保证是整数,且范围不能超过200

deleteProperty(): 删除,拦截:

has(): 检测有没有

apply() :拦截方法


Reflect.apply(调用的函数,this指向,参数数组);

fn.call()
fn.apply() 类似

Reflect: 反射
Object.xxx 语言内部方法

    Object.defineProperty

放到Reflect对象身上

通过Reflect对象身上直接拿到语言内部东西

'assign' in Object    ->   Reflect.has(Object, 'assign')

delete json.a       ->   Reflect.deleteProperty(json, 'a');
上一篇 下一篇

猜你喜欢

热点阅读