ES6 及以上引入的新特性

23 阅读1分钟

1 let、const

let 和 const 关键字:用于更灵活的变量声明,let 声明的变量具有块级作用域,const 用于声明常量。

let x = 5;
const y = 10;

2 箭头函数

箭头函数:提供了更简洁的函数定义方式。

const multiply = (a, b) => a * b;

3 模板字符串

模板字符串:可以更方便地进行字符串拼接和格式化。

const name = 'John';
console.log(`Hello, ${name}!`);

4 解构赋值

解构赋值:方便从数组或对象中提取值。

const [a, b] = [1, 2];
const { name, age } = { name: 'Alice', age: 25 };

5 扩展运算符(...)

扩展运算符(...):用于数组和对象的操作。

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1,...arr2];

const obj1 = { x: 1, y: 2 };
const obj2 = { z: 3 };
const merged = {...obj1,...obj2 };

6 Promise 对象

Promise 对象:用于处理异步操作。

function fetchData() {
  return new Promise((resolve, reject) => {
    // 模拟异步操作
    setTimeout(() => {
      if (Math.random() > 0.5) {
        resolve('Data fetched successfully!');
      } else {
        reject('Error fetching data.');
      }
    }, 1000);
  });
}
fetchData()
.then(result => console.log(result))
.catch(error => console.error(error));

7 async/await

async/await:使异步代码看起来更像同步代码。

async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    throw error;
  }
}
fetchData().then(data => console.log(data));

8 类(class)

类(class):提供了更清晰的面向对象编程方式。

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}
const person = new Person('John', 30);
person.sayHello();

9 模块(import 和 export)

模块(import 和 export):更好地组织和复用代码。

// module.js
export const message = 'Hello from module!';

// main.js
import { message } from './module';
console.log(message);

10 新的对象方法和数组方法

新的对象方法和数组方法,如 Object.assign()Array.prototype.includes() 等。