JavaScript(ES6版本)语法基础

在学习react过程中,发现自己js的基础还很薄弱,一些ES6版本里常见的内容在这里做下总结。

一,var let 和 const

let,var,const的区别:
https://www.jianshu.com/p/9f7f053f7204
https://baijiahao.baidu.com/s?id=1621787284851612777&wfr=spider&for=pc

二,解构赋值

数组解构赋值,对象解构赋值

{
    let a,b,rest;
    [a,b]=[1,2];  //数组解构赋值
   // let a=1,b=2; 之前的方法
    console.log(a,b);
}

{
    let a,b,rest;
    [a,b,...rest]=[1,2,3,4,5,6];
    console.log(a,b,rest);
}

{
    let a,b;
    ({a,b}={a:1,b:2});   //对象解构赋值
    console.log(a,b);

}
//对象解构赋值
{
    let o={p:42,q:true};
    let {p,q}=o;
    console.log(p,q);
}

//对象解构赋值,默认值的处理
{
    let {a=10,b=5}={a:3};

    console.log(a,b);
}

{
    let a,b,c,rest;
    [a,b,c=3]=[1,2];  //数组解构赋值,给3一个默认值
    // [a,b,c]=[1,2];  如果没能配对,会出现未定义
    console.log(a,b,c);
}

数组解构赋值应用场景

1.取函数的返回值

{
    function f() {
        return [1,2];
    }

    let a,b;
    [a,b]=f();
    console.log(a,b);
}

2.变量交换

{
    let a=1;
    let b=2;
    [a,b]=[b,a];

    console.log(a,b);
}

3.接受函数返回值,可选择

{
    function f1() {
        return[1,2,3,4,5];
    }
    let a,b,c;
    [a,,,b]=f1();

    console.log(a,b); //返回的是多个值,可以只关心自己想要的
}

4.如果不确定长度,接受多个值

{
    function f1() {
        return[1,2,3,4,5];
    }
    let a,b,c;
    [a,...b]=f1();

    console.log(a,b);
}

对象解构赋值应用场景

取json对象的某些值

{
    let Data={
        title:'abc',
        test:[{
            title:'test',
            desc:'description'
        }]
    }
    let {title:a,test:[{title:b}] }=Data;
    console.log(a,b);
}

三,函数相关

参数默认值

{
    function test(x,y='world') {
        console.log(x,y);
    }
    test('hello');
}

作用域
以函数内部参数的优先

{
    let x='test';
    function f(x,y=x) {
        console.log(x,y);//输出的是 kill kill
    }
    f('kill');
}

{
    let x='test';

    function f(c,y=x) {
        console.log(c,y);  //输出的是 kill test
    }
    f('kill');

}

rest参数

{
    function  test3(...arg) {
        for(let v of arg){
            console.log('rest',v);
        }
    }
    test3(1,2,3,'a','b','c');

}

箭头函数

{
    let arrow =  v => v*2; //arrow是函数名,v是参数,v*2是返回值
    console.log(arrow(3));
    let arrow2 =  () => 5;
    console.log(arrow2());
}

this绑定
尾调用

四,模块化

import 引入模块
export 导出模块

你可能感兴趣的:(JavaScript(ES6版本)语法基础)