Es6新特性知识梳理

399 阅读2分钟

一、字符串扩展

1、ES6为字符串扩展了几个新的API:

  • includes():返回布尔值,表示是否找到了参数字符串。
  • startWith():返回布尔值,表示参数字符串是否在原字符串的头部。
  • endWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

ES6中提供了来作为字符串模板标记。

在两个`之间的部分都会被作为字符串的值,不管你任意换行,甚至加入js脚本键盘是的1的左侧,tab的上侧,esc的正下方

二、解构表达式

数组结构

比如有一个数组:

let arr = [1,2,3]

我想获取其中的值,只能通过角标。ES6可以这样:

const [x,y,z] = arr;// x,y,z将与arr中的每个位置对应来取值
// 然后打印
console.log(x,y,z);

结果:

对象结构

例如有个person对象:

const person = {
    name:"jack",
    age:24,
    language: ['java','js','css']
}

可以这么写:

// 结构表达式取值
const {name, age, language} = person;
console.log(name);
console.log(age);
console.log(language);

结果:

如果想要用其它变量接受,需要额外指定别名:

  • {name:n}: name是person中的属性名,冒号后面的n是解构后要赋值给的变量。

函数优化

函数参数默认值

在ES6以前,我们无法给一个函数参数设置默认值,只能采用变通写法:

function add(a , b) {
         // 判断b是否为空,为空给默认值1
        b = b || 1;
        return a + b;
}
// 传一个参数
console.log(add(10));

现在可以这么写:

function add(a , b = 1) {
    return a + b;
}
// 传一个参数
console.log(add(10));

箭头函数

ES6中定义函数的简写方式:

一个参数时:

var print = function (ogj) {
    console.log(obj);
}
//  简写为:
var sum2 = { a,b } => a+b;

代码不止一行,可以用{}括起来

var sum3 = {a,b} => {
    return a + b;
}

对象的函数属性简写

比如一个Person对象,里面有eat方法:

let person = {
    name: "jack",
    //以前:
    eat:function (food) {
        console.log(this.name + "在吃" + food);
},
// 箭头函数版:
eat2:food => console.log(person.name + "在吃" + food),// 这里拿不到this
// 简写版:
eat(food) {
        console.log(this.name + "在吃" + food);
    }
}

箭头函数结合解构

一个函数:

const person = {
    name:"jack",
    age:21,
    language: ['java','js','css']
}

function hello(person) {
    console.log("hello," + person.name)
}

用箭头函数和结构表达式

var hi = ({name}) =>  console.log("hello," + name)