技术实践

常用的ECMAScript6语法有哪些?

ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体

羊先生的头像
羊先生2022.03.09 · 2 分钟阅读 · 54 阅读
常用的ECMAScript6语法有哪些?封面
文章正文还需 2 分钟

let, const, class, import, export, export default, Promise, async, await, for await, Object.values,Object.kes, array.form array.reduce

for...of 和 for...in

for...of 用于遍历一个迭代器,如数组:

js 复制代码
let letter = ['a', 'b', 'c'];
letter.size = 3;
for (let letter of letters) {
  console.log(letter);
}
// 结果: a, b, c

for...in 用来遍历对象中的属性:

js 复制代码
let stu = ['Sam', '22', '男'];
stu.size = 3;
for (let stu in stus) {
  console.log(stu);
}
// 结果: Sam, 22, 男

对象超类

ES6 允许在对象中使用 super 方法:

js 复制代码
ar parent = {
  foo() {
    console.log("Hello from the Parent");
  }
}
 
var child = {
  foo() {
    super.foo();
    console.log("Hello from the Child");
  }
}
 
Object.setPrototypeOf(child, parent);
child.foo(); // Hello from the Parent
             // Hello from the Child

函数的参数默认值

js 复制代码
// ES6之前,当未传入参数时,text = 'default';
function printText(text) {
    text = text || 'default';
    console.log(text);
}

// ES6;
function printText(text = 'default') {
    console.log(text);
}

printText('hello'); // hello
printText();// default

箭头函数(Arrow Functions)

ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体;
箭头函数最直观的三个特点:

  1. 不需要 function 关键字来创建函数
  2. 省略 return 关键字
  3. 继承当前上下文的 this 关键字
js 复制代码
// ES5
var add = function (a, b) {
    return a + b;
};
// 使用箭头函数
var add = (a, b) => a + b;

// ES5
[1,2,3].map((function(x){
    return x + 1;
}).bind(this));
    
// 使用箭头函数
[1,2,3].map(x => x + 1);

ES6中常用的10个新特性讲解

ES6常用语法总结

ES6 入门教程